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   风zk  阅读(30)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示