关闭

Swift 控制流

110人阅读 评论(0) 收藏 举报
分类:

// 控制流包含 if switch for in while repeat-while
        // 1.fot in 遍历数组
        let individualScores = [77, 11, 12, 45, 111]
        var teamScore = 0
        for value in individualScores {
            if value > teamScore {
                teamScore = value
                print(teamScore)
            }
        }
        // 2.for in 遍历字典
        let numbers = ["OM1": [1, 2, 3, 4],
                       "OM2": [5, 6, 7, 8],
                       "OM3": [9, 10, 11, 12]]
        var largest = 0
        for (key, values) in numbers {
            for value in values {
                if value > largest {
                    largest = value
                    print(largest)
                    print(key)
                }
            }
        }
        
        // if let
        // optionalName 为 nil, 括号中的代码将不会被执行
        let optionalName: String? = "xiaoMing"
        var greeting = "Hello"
        if let name = optionalName {
            greeting = "Hello, \(name)"
            print(greeting)
        }
        // switch
        let gather = "red"
        switch gather {
        case "blcak":
            print ("This is a \(gather)")
        case "red":
            print ("This is a \(gather)")
        default:
            print("Didn't find")
        }
        // while
        var n = 2
        while n < 120 {
            n = n * 2
        }
        print(n)
        // repeat while
        var m = 2
        repeat {
           m = m * 2
        } while m < 120
        // 注释: 此时While 与 repeat While 的效果相同
        
        // 范围标识
        var count = 0
        for z in 0..<6 {
            count += z
        }
        print(count)
        
        var count2 = 0
        for var i = 0; i < 6; ++i {
            count2 += i
        }
        print(count2)
        // 注释: 使用..<范围不包含上界,如果想包含的话需要要使用...


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:27028次
    • 积分:1067
    • 等级:
    • 排名:千里之外
    • 原创:80篇
    • 转载:9篇
    • 译文:1篇
    • 评论:0条