Swift(二)流程控制

weixin_34075551發表於2016-10-23
1599230-6fa066d61c8151c2.jpeg
5227f560d999a433a2daad3147251ee207625d49382ce-1umldo_fw658.jpeg
var optionalName: String? = "John Appleseed"
        optionalName = nil
        var greeting = "Hello! "
        //判斷optionalName 是否為nil
        if let name = optionalName {
            greeting = "Hello, \(name)"
        }else {
            print(greeting);
        }  
let vegetable = "red pepper"
        switch vegetable {
        case "celery":
            let vegetableComment = "Add some raisins and make ants on a log."
            print(vegetableComment)
        case "cucumber", "watercress":
            let vegetableComment = "That would make a good tea sandwich."
            print(vegetableComment)
            //次初需要注意, let ... where ... 意思是根據引數進行額外的條件, 意思就是x是否以pepper結尾
        case let x where x.hasSuffix("pepper"):
            let vegetableComment = "Is it a spicy \(x)?"
            print(vegetableComment)
        default:
            let vegetableComment = "Everything tastes good in soup."
            print(vegetableComment)
        }

let interestingNumbers = [
            "Prime": [2, 3, 5, 7, 11, 13],
            "Fibonacci": [1, 1, 2, 3, 5, 8],
            "Square": [1, 4, 9, 16, 25],
            ]
        var largest = 0
        //如果註釋print(key), 則會提示Immutable value 'key' never used, 建議你使用'_'替換, 如果你和我一樣是一個追求完美的人, 有強迫症, 那就替換掉, 如果沒有強迫症, 不替換也沒事
        //在swift裡面, 如果你宣告一個變數, 如果你沒有使用它, 會提醒你把變數宣告為常量let, 如果在let下, 你還沒有使用它,Initialization of immutable value 'x' was never used, 希望你使用'_'替換
        for (key, numbers) in interestingNumbers {
            for number in numbers {
                if number > largest {
                    largest = number
                    //print(key)
                }
            }
        }
        print(largest)
//此數需要注意, For迴圈的寫法和swift2有所區別
        //..兩個點不包括上界
        var firstForLoop = 0
        for i in 0..<3 {
            firstForLoop += i
            print("-----")
        }
        print(firstForLoop)
        
        //三個點包括上界
        var secondForLoop = 0
        for _ in 0 ... 3 {
            secondForLoop += 1
            print("++++++")
        }
        print(secondForLoop)
        //反轉
        for i in (1...10).reversed() {
            print(i)
        }
        
        //不包括10
        for i in stride(from: 0, to: 10, by: 2) {
            print(i)
        }

        //包括10
        for i in stride(from: 0, through: 10, by: 2) {
            print(i)
        }
//Swift語言中, 判斷條件必須是一個表示式, 這和Objective-C 中不同, 在OC中, 字需要是一個非0的值就可以了.
let i = 1
if i {
    // this example will not compile, and will report an error
}

相關文章