05:控制流:for循环、while循环、guard else 提前退出

正文

for循环、while循环、guard else 提前退出

    /* for循环
    */
    private func testForLoop() {
        // 1: 遍历数组
        let names = ["Anna", "Alex", "Brian", "Jack"]
        for name in names {
            print("Hello, \(name)!")
        }
        
        // 2: 遍历字典
        let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
        for (animalName, legCount) in numberOfLegs {
            print("\(animalName)s have \(legCount) legs")
        }
        
        // 3: 遍历区间
        for index in 1...5 {
            print("\(index) times 5 is \(index * 5)")
        }
        
        // _ 下划线字符(在循环变量那里使用的那个)导致单个值被忽略并且不需要在每次遍历循环中提供当前值的访问
        // 如果你不需要序列的每一个值,你可以使用下划线来取代遍历名以忽略值。
        // 3的10次方
        let base = 3
        let power = 10
        var answer = 1
        for _ in 1...power {
            answer *= base
        }
        print("\(base) to the power of \(power) is \(answer)")
    }
    
    /* While 循环
     while 循环执行一个合集的语句直到条件变成 false 。这种循环最好在第一次循环之后还有未知数量的遍历时使用。Swift 提供了两种 while 循环:
     while 在每次循环开始的时候计算它自己的条件;
     repeat-while 在每次循环结束的时候计算它自己的条件。
     */
    private func testWhileLoop() {
        
        var i = 0
        let j = 10
        while i < j {
            print("索引是:\(i)")
            i += 1
        }
        
        var m = 0
        let n = 10
        repeat {
            print("--->>>:索引是:\(m)")
            m += 1
        } while m < n
    }
    
    // 3:提前退出guard else 语句
    
    private func testGuardElseFunction(dic: [String: String]) {
        guard let name = dic["name"] else {
            return
        }
        print("Hello \(name)!")
        
        // 如果没有people这个key的话,直接退出
        guard let people = dic["people"] else {
            return
        }
        print("I hope the weather is nice in \(people).")
    }

 

posted on 2023-02-26 17:44  风zk  阅读(22)  评论(0编辑  收藏  举报

导航