• <small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small><xmp id="w8oog"><td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><xmp id="w8oog"><td id="w8oog"></td>
  • <td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small>
  • <small id="w8oog"></small><td id="w8oog"></td>
    免費開源的iOS開發學習平臺

    Swift: 6.1 語句和流程控制--循環語句

    跟C語言和Objective-C語言類似,Swift也提供了循環、條件判斷流程控制結構和break、continue、fallthrough等語句。Swift使用for-in循環結構來遍歷數組(array)、字典(dictionary)、區間(range)、字符串(string)和其他序列類型。Swift中的switch語句比Objective-C中的更加強大。在Objective-C語言中,如果某個 case 不小心漏寫了break,這個case 就會貫穿(fallthrough)至下一個case,而在Swift中無需寫break,所以不會發生這種貫穿(fallthrough)的情況。case 還可以匹配更多的類型模式,包括區間匹配(range matching)、元組(tuple)、特定類型的描述和進行值綁定。switch的case語句中匹配的值可以是由case體內部臨時的常量或者變量決定,也可以由where分句描述更復雜的匹配條件。

    for循環語句

    • Swift 3.0 中移除了C語言風格的循環語句,下面代碼在Swift 3.0中會報錯的。
    var j=0
    for j=0;j<5;j+=1 {
        print("j=\(j)")
    }
    
    • Swift提供了for-in語句來循環遍歷區間、數組、字符串、字典以及集合等序列值類型。如果循環過程中用不到序列中的值,可以使用下劃線"_"來作為變量名忽略該值。
    let base = 2
    let power = 10
    var result = 1
    for _ in 1...power{
        result *= base
    }
    print("\(base) 的 \(power) 次方等于 \(result)")
    //打印結果:2 的 10 次方等于 1024
    

    while循環語句

    • Swift中的while循環語句跟Objective-C中的用法是一致的。不過,Swift使用repeat-while語句來對應替換Objective-C中的do-while語句。
    let two = 2
    let one = 1
    repeat {
        print("無論如何都會執行一次")
    } while two < one
    //執行結果:無論如何都會執行一次
    

    示例代碼

    //遍歷區間
    for i in 0..<10{
        print(i, terminator: ",");
    }
    print("")
    //遍歷數組
    let arr = Array.init(repeating: 1.0, count: 5)
    for val in arr{
        print(val,terminator:",")
    }
    print("")
    //遍歷字典
    let dic = ["name":"張三","age":"15","birthday":"1990-06-11"]
    for (key,val) in dic
    {
        print("\(key):\(val)")
    }
    //遍歷集合
    let set:Set = ["小明","小紅","小梅"]
    for val in set{
        print(val,terminator:",")
    }
    print("")
    //while循環
    var index = 0
    while index<10 {
        print(index,terminator:",")
        index += 1
    }
    print("")
    //repeat-while循環
    var index1 = 0
    repeat {
        print(index1,terminator:",")
        index1 += 1
    }while index1 < 10
    
    

    代碼執行結果如下圖。

    示例代碼

    https://github.com/99ios/23.6.1

    ijzzijzzij亚洲大全|天天狠天天透天干天天|日本一本加勒比五月天伊人久久|久久久噜噜噜久久中文字幕色伊伊
  • <small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small><xmp id="w8oog"><td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><xmp id="w8oog"><td id="w8oog"></td>
  • <td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small>
  • <small id="w8oog"></small><td id="w8oog"></td>