Control Flow Of Swift

jopen 8年前發布 | 12K 次閱讀 Swift Apple Swift開發

前言

Swift提供了類似C語言的流程控制結構,包括可以多次執行任務的for和while循環。還有基于特定條件選擇執行不同代碼分支的if、guard和switch語句,還有控制流程跳轉到其他代碼的break和continue語句。

Swift增加了for-in循環,用來更簡單地遍歷數組、字典、區間、字符串和其他序列類型。

Swift的switch語句比C語言中更加強大。在C語言中,如果某個case不小心漏寫了break,這個case就會貫穿至下一個case,而Swift無需寫break,所以不會發生這種貫穿的情況。case 還可以匹配更多的類型模式,包括區間匹配(range matching)、元組(tuple)和特定類型的描述。switch的case語句中匹配的值可以是由case體內部臨時的常量或者變量決定,也可以由where分句描述更復雜的匹配條件。

for循環(For Loops Statement)

  • for:與C語言一樣的for循環
  • for-in:快速遍歷集合、序列等

for-in遍歷range(其中…表示閉區間[1,5]):

 
forindexin 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
 
// 它可以轉換for循環為:
forvarindex = 1; index <= 5; ++index {
  // ...
}
 

若我們不要獲取值,可以用下劃線(_)過濾,這種用法很常見:

 
letbase = 3
letpower = 10
varanswer = 1
 
// 三個點表示全閉區間[1, power]
for _ in 1...power {
    answer*= base
}
 
// 兩個點加一個<就是左閉右開[1, 5)
varsum = 0
for _ in 1..<5 {
  sum += 1
}
 

常見的遍歷數組方法:

 
letnames = ["Anna", "Alex", "Brian", "Jack"]
for namein names {
    print("Hello, \(name)!")
}
 
// or
for (name, index) in names.enumerate() {
  // 也是很常用的
}
 

常見的遍歷字典:

 
letnumberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
 
// 我們知道字典中的鍵值對是用元組表示的,所以可以直接通過元組來訪問
 

while循環(While Loop Statement)

  • while循環,每次在循環開始時計算條件是否符合;
  • repeat-while循環,每次在循環結束時計算條件是否符合。用法與Objective-C中的do-while完全一樣。

注意:沒有do-while而是repeat-while

 
varindex = 10
while index > 0 {
  index--
}
print(index)// 0
 
index = 0
repeat {// 沒有do-while了,只有repeat-while
  print("test repeat")
  index++
} while index < 3
 

if條件語句(If Condition Statement)

If條件為真假值,要么為true,要么為false。

 
// 條件只有index值為3,結果才為true,才會打印。
if index == 3 {
  print("3")
}
 

guide語句(Guide Condition Statement)

guide 語法與if不同,如果條件為真,則不進入else分支,否則進入。 guide 語義是守衛的意思,也就是說,只要滿足條件,什么事都沒有,否則就會進入else分支。

 
// 在函數內部,判斷必傳參數為空時,直接退出函數,這種用法很常用。
guardletname = dict["name"]else {
    return
}
 

switch語句(Switch Statement)

swift中的Switch分支與Objective-C中的switch有很多不同的地方:

  • swift中不需要為每個case手動寫break
  • swift中case支持區間匹配
  • swift中的case支持元組
  • swift中的case支持值綁定
  • swift中的case支持where條件過濾
  • swift中的case可以放置多個值

不用手寫break,也不會隱式貫穿:

 
varvalue = 1
switch value {
case 1:
  print("only print 1")
case 2:
  print("only print 2")
default:
  print("on matched value")
}
// "only print 1\n"
 

支持匹配區間:

 
letapproximateCount = 62
letcountedThings = "moons orbiting Saturn"
varnaturalCount: String
switch approximateCount {
case0:
    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).")
// 輸出 "There are dozens of moons orbiting Saturn."
 

支持元組,對于不需要獲取的值,可以用 _ 過濾:

 
lethttpError = (404, "Http Not Found")
switch httpError {
case let (code, _) wherecode == 404:
  print(httpError.1)
case let (code, msg) wherecode == 502:
  print(msg)
  
default:
  print("default")
}
 

支持值綁定:

 
letanotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0, 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過濾條件:

 
letpoint = (1, 3)
switch point {
case let (x, y) where x > y:
  print("x > y")
case let (x, _) where x > 2:
  print("x > 2")
case let (1, y) where y > 4:
  print("y > 4 and x == 1")
case let (x, y) where x >= 1 && y <= 10:
  print("ok")// ok
default:
  print("error")
}
 

支持一個case多個值:

 
letnumberSymbol: Character = "三"  // 簡體中文里的數字 3
varpossibleIntegerValue: Int?
switch numberSymbol {
case "1", "?", "一", "?":
    possibleIntegerValue = 1
case "2", "?", "二", "?":
    possibleIntegerValue = 2
case "3", "?", "三", "?":
    possibleIntegerValue = 3
case "4", "?", "四", "?":
    possibleIntegerValue = 4
default:
    break
}
 

控制轉移語句(Control Transfer Statements)

swift有五種控制轉移語句:

  • continue:跳過本次循環,直接進入下一循環
  • break:中斷最近的循環或者中斷某個標簽(下一小節說明)
  • fallthrough:用于switch分支貫穿分支
  • return:用于函數返回
  • throw:用于拋出異常

用 continue 跳過不滿足條件的:

 
letpuzzleInput = "great minds think alike"
varpuzzleOutput = ""
forcharacterin puzzleInput.characters {
    switch character {
    case "a", "e", "i", "o", "u", " ":
        continue
    default:
        puzzleOutput.append(character)
    }
}
print(puzzleOutput)
// 輸出 "grtmndsthnklk"
 

用break退出循環:

 
forindexin 1...5 {
  if index >= 3 {
    break
  }
}
 
// 在swift中用break,就會直接退出該swift語句
index = 10
forindexin 20..<100 {
    switch index {
        case let x where x < 40:
        print(x)
    case let x where x > 100:
        break
    default:
        break
}
 

用fallthrough貫穿swift的case:

 
letintegerToDescribe = 5
vardescription = "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."
 

標簽語句

比如有時候需要在滿足某個條件的時候就跳去執行某段代碼,那么這時候用標簽語句就很好用:

語法如下:

 
labelname: while condition {
    statements
}
 

官方的一個例子:

 
gameLoop: while square != finalSquare {
    if ++diceRoll == 7 { diceRoll = 1 }
    switch square + diceRoll {
    case finalSquare:
        // 到達最后一個方塊,游戲結束
        break gameLoop
    case letnewSquarewherenewSquare > finalSquare:
        // 超出最后一個方塊,再擲一次骰子
        continue gameLoop
    default:
        // 本次移動有效
        square += diceRoll
        square += board[square]
    }
}
print("Game over!")
 

檢查API可用性

語法如下:

 
if #available(iOS 9, OSX 10.10, *) {
    // 在 iOS 使用 iOS 9 的 API, 在 OS X 使用 OS X v10.10 的 API
} else {
    // 使用先前版本的 iOS 和 OS X 的 API
}
 

詳細如何使用,請閱讀文章:Swift檢測API可用性

寫在最后

本篇博文是筆者在學習Swift 2.1的過程中記錄下來的,可能有些翻譯不到位,還請指出。另外,所有例子都是筆者練習寫的,若有不合理之處,還望指出。

學習一門語言最好的方法不是看萬遍書,而是動手操作、動手練習。如果大家喜歡,可以關注哦,盡量2-3天整理一篇Swift 2.1的文章。這里所寫的是基礎知識,如果您已經是大神,還請繞路!

關注我

如果在使用過程中遇到問題,或者想要與我交流,可加入有問必答 QQ群: 324400294

關注微信公眾號: iOSDevShares

關注新浪微博賬號:標哥Jacky

支持并捐助

如果您覺得文章對您很有幫助,希望得到您的支持。您的捐肋將會給予我最大的鼓勵,感謝您的支持!

支付寶捐助 微信捐助

來自: http://www.henishuo.com/control-flow-of-swift/

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!