swift八-控制流

/*For-In 循環
While 循環
? 條件語句
? 控制轉移語句(Control Transfer Statements)
? 提前退出 (
? 檢測 API 可用性 */

    //使用 for-in 循環來遍歷一個 合中的所有元素
    for index in 1...5 {
        print("\(index) times 5 is \(index * 5)")
    }
    //如果你不需要區間序列內每一項的值,你可以使用下劃線( _ )替代變量名來忽略這個值:
    let base = 3
    let power = 10
    var answer = 1
    for _ in 1...power {
        answer *= base
    }
    print("\(base) to the power of \(power) is \(answer)")
    
    
    //使用 for-in 遍歷一個數組所有元素:
    let names = ["Anna", "Alex", "Brian", "Jack"]
    for name in names {
        print("Hello, (name)!")
    }
    
    
    //while 循環
    //while 循環會一直運行一段語句直到條件變成 false 。這類循環適合使用在第一次迭代前,迭代次數未知的情況下
    //while循環,每次在循環開始時計算條件是否符合;
    //repeat-while循環,每次在循環結束時計算條件是否符合。
    
    
    /*游戲的規則如下:
    ? 游戲盤面包括 25 個方格,游戲目標是達到或者超過第 25 個方格;
    ? 每一輪,你通過擲一個六面體骰子來確定你移動方塊的步數,移動的路線由上圖中橫向的虛線所示; 
    ? 如果在某輪結束,你移動到了梯子的底部,可以順著梯子爬上去;
    ? 如果在某輪結束,你移動到了蛇的頭部,你會順著蛇的身體滑下去。*/
    let finalSquare = 25
    var board = [Int](repeating: 0, count: finalSquare + 1)
    
    board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
    board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08

    var square = 0
    var diceRoll = 0
    while square < finalSquare {
        // 擲骰子
        diceRoll += 1
        if diceRoll == 7 { diceRoll = 1 } // 根據點數移動
        square += diceRoll
        if square < board.count {
            // 如果玩家還在棋盤上,順著梯子爬上去或者順著蛇滑下去
            square += board[square]
        }
    }
    print("Game over!")

    //Repeat-While
    //while 循環的另外一種形式是 repeat-while ,它和 while 的區別是在判斷循環條件之前,先執行一次循環的代碼 塊。然后重復循環直到條件為 false 。
    
    //條件語句 If
    
    var temperatureInFahrenheit = 30
    if temperatureInFahrenheit <= 32 {
        print("It's very cold. Consider wearing a scarf.")
    }
    // 輸出 "It's very cold. Consider wearing a scarf."
    
    temperatureInFahrenheit = 40
    if temperatureInFahrenheit <= 32 {
        print("It's very cold. Consider wearing a scarf.")
    } else {
        print("It's not that cold. Wear a t-shirt.")
    }
    // 輸出 "It's not that cold. Wear a t-shirt."
    
    temperatureInFahrenheit = 90
    if temperatureInFahrenheit <= 32 {
        print("It's very cold. Consider wearing a scarf.")
    } else if temperatureInFahrenheit >= 86 {
        print("It's really warm. Don't forget to wear sunscreen.")
    } else {
        print("It's not that cold. Wear a t-shirt.")
    }
    // 輸出 "It's really warm. Don't forget to wear sunscreen."
    
    
    //switch
    
    //switch 語句會嘗試把某個值與若干個模式(pattern)進行匹配。根據第一個匹配成功的模式, switch 語句會執 行對應的代碼。當有可能的情況較多時,通常用 switch 語句替換 if 語句。
    //switch 語句最簡單的形式就是把某個值與一個或若干個相同類型的值作比較:
    
    let someCharacter: Character = "z"
    switch someCharacter {
    case "a":
        print("The first letter of the alphabet")
    case "z":
        print("The last letter of the alphabet")
    default:
        print("Some other character")
    }
    // 輸出 "The last letter of the alphabet"
    
    //為了讓單個case同時匹配 a 和 A ,可以將這個兩個值組合成一個復合匹配,并且用逗號分開:
    let anotherCharacter: Character = "a"
    switch anotherCharacter {
    case "a", "A":
        print("The letter A")
    default:
        print("Not the letter A")
    }
    // 輸出 "The letter A
    
    
    //區間匹配
    //case 分支的模式也可以是一個值的區間。下面的例子展示了如何使用區間匹配來輸出任意數字對應的自然語言格 式:
    
    let approximateCount = 62
    let countedThings = "moons orbiting Saturn"
    var naturalCount: String
    switch approximateCount {
    case 0:
        naturalCount = "no"
    case 1..<5:
        naturalCount = "a few"
    case 5..<12:
        naturalCount = "several"
    case 12..<100:
        naturalCount = "dozens of"
    case 100..<1000:
        naturalCount = "hundreds of"
    default:
        naturalCount = "many"
    }
    print("There are \(naturalCount) \(countedThings).")
    
    
    //元組
    //我們可以使用元組在同一個 switch 語句中測試多個值。元組中的元素可以是值,也可以是區間。另外,使用下劃 線( _ )來匹配所有可能的值。
    //下面的例子展示了如何使用一個 (Int, Int) 類型的元組來分類下圖中的點(x, y):
    let somePoint = (1, 1)
    switch somePoint {
    case (0, 0):
        print("(0, 0) is at the origin")
    case (_, 0):
        print("(\(somePoint.0), 0) is on the x-axis")
    case (0, _):
        print("(0, \(somePoint.1)) is on the y-axis")
    case (-2...2, -2...2):
        print("(\(somePoint.0), \(somePoint.1)) is inside the box")
    default:
        print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
    }
    // 輸出 "(1, 1) is inside the box"

    //值綁定(Value Bindings)
    //case 分支允許將匹配的值綁定到一個臨時的常量或變量,并且在case分支體內使用 —— 這種行為被稱為值綁 定(value binding),因為匹配的值在case分支體內,與臨時的常量或變量綁定。
    //下面的例子展示了如何在一個 (Int, Int) 類型的元組中使用值綁定來分類下圖中的點(x, y):
    let anotherPoint = (2, 0)
    switch anotherPoint {
    case (0, let y):
        print("on the x-axis with an x value of \(y)")
    case (2, let y):
        print("on the y-axis with a y value of \(y)")
    case let (x, y):
        print("somewhere else at (\(x), \(y))")
    }
    // 輸出 "on the x-axis with an x value of 2"
    
    //Where
    //case 分支的模式可以使用 where 語句來判斷額外的條件。
    //下面的例子把下圖中的點(x, y)進行了分類:
    
    let yetAnotherPoint = (1, -1)
    switch yetAnotherPoint {
    case let (x, y) where x == y:
        print("(\(x), \(y)) is on the line x == y")
    case let (x, y) where x == -y:
        print("(\(x), \(y)) is on the line x == -y")
    case let (x, y):
        print("(\(x), \(y)) is just some arbitrary point")
    }
    // 輸出 "(1, -1) is on the line x == -y"
    
   // 復合匹配
    //當多個條件可以使用同一種方法來處理時,可以將這幾種可能放在同一個 case 后面,并且用逗號隔開。當case后 面的任意一種模式匹配的時候,這條分支就會被匹配。并且,如果匹配列表過長,還可以分行書寫:
    
    let somesCharacter: Character = "e"
    switch somesCharacter {
    case "a", "e", "i", "o", "u":
        print("\(somesCharacter) is a vowel")
    case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
         "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
        print("\(somesCharacter) is a consonant")
    default:
        print("\(somesCharacter) is not a vowel or a consonant")
    }
    // 輸出 "e is a vowel"

    

    //控制轉移語句
    /*
     ? continue
     ? break
     ? fallthrough 
     ? return
     ? throw
     */
    
    //continue
    //continue 語句告訴一個循環體立刻停止本次循環,重新開始下次循環。就好像在說“本次循環我已經執行完 了”,但是并不會離開整個循環體。
    let puzzleInput = "great minds think alike"
    var puzzleOutput = ""
    for character in puzzleInput.characters {
        switch character {
        case "a", "e", "i", "o", "u", " ":
            continue
        default:
            puzzleOutput.append(character)
        }
    }
    print(puzzleOutput)
    // 輸出 "grtmndsthnklk"
    
    //break:break 語句會立刻結束整個控制流的執行。當你想要更早的結束一個 switch 代碼塊或者一個循環體時,你都可以 使用 break 語句。
    let numberSymbol: Character = "三" // 簡體中文里的數字 3 
    var possibleIntegerValue: Int?
    switch numberSymbol {
    case "1", "?", "一", "?":
        possibleIntegerValue = 1
    case "2", "?", "二", "?":
        possibleIntegerValue = 2
    case "3", "?", "三", "?":
        possibleIntegerValue = 3
    case "4", "?", "四", "?":
        possibleIntegerValue = 4
    default:
        break
    }
    if let integerValue = possibleIntegerValue {
        print("The integer value of \(numberSymbol) is \(integerValue).")
    } else {
        print("An integer value could not be found for \(numberSymbol).")
    }
    // 輸出 "The integer value of 三 is 3."
    
    
    //貫穿 fallthrough
    let integerToDescribe = 5
    var description = "The number \(integerToDescribe) is"
    switch integerToDescribe {
    case 2, 3, 5, 7, 11, 13, 17, 19:
        description += " a prime number, and also"
        fallthrough
    default:
        description += " an integer."
    }
    print(description)
    // 輸出 "The number 5 is a prime number, and also an integer."
    
    //提前退出 return
    
    //像 if 語句一樣, guard 的執行取決于一個表達式的布爾值。我們可以使用 guard 語句來要求條件必須為真 時,以執行 guard 語句后的代碼。不同于 if 語句,一個 guard 語句總是有一個 else 從句,如果條件不為真則執 行 else 從句中的代碼。
    
    func greet(person: [String: String]) {
        
        guard let name = person["name"] else {
            return
        }
        print("Hello \(name)")
        
        guard let location = person["location"] else {
            
            print("I hope the weather is nice near you.")
            return
        }
        
        print("I hope the weather is nice in \(location).")
    }
    greet(person: ["name": "John"])
    // 輸出 "Hello John!"
    // 輸出 "I hope the weather is nice near you." greet(["name": "Jane", "location": "Cupertino"]) // 輸出 "Hello Jane!"
    // 輸出 "I hope the weather is nice in Cupertino."
    
    
    //檢測API可用性
    //我們在 if 或 guard 語句中使用 可用性條件(availability condition) 去有條件的執行一段代碼,來在運行時判 斷調用的API是否可用。編譯器使用從可用性條件語句中獲取的信息去驗證,在這個代碼塊中調用的 API 是否可 用。
    
    if #available(iOS 10, macOS 10.12, *) {
        // 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
    } else {
        // 使用先前版本的 iOS 和 macOS 的 API
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Swift 提供了類似 C 語言的流程控制結構,包括可以多次執行任務的for和while循環,基于特定條件選擇執行...
    窮人家的孩紙閱讀 722評論 1 1
  • [The Swift Programming Language 中文版]本頁包含內容: Swift提供了多種流程控...
    風林山火閱讀 588評論 0 0
  • 啊啊啊啊啊
    蛋堡123閱讀 249評論 0 0
  • 五年級的2月14, 和喜歡的人在QQ上約定一起去滑冰。 纏著媽媽在那天下午 把我帶到溜冰場, 然后假裝巧遇, 一起...
    燕小艾閱讀 159評論 0 0
  • “過年了,回來吧!亮子,媽,想你了,今年,你一定要回來。” “媽,我會的,我一定會回來的,你放心”掛斷母親的電話,...
    寫不好的三閱讀 519評論 4 4