Swift05/90Days - 控制流

控制流

控制流基本上大同小異,在此列舉幾個比較有趣的地方。html

switch

Break

文檔原文是 No Implicit Fallthrough ,粗暴的翻譯一下就是:不存在隱式貫穿。其中 Implicit 是一個常常出現的詞,中文原意是:「含蓄的,暗示的,隱蓄的」。在 Swift 中一般表示默認處理。好比這裏的隱式貫穿,就是指傳統的多個 case 若是沒有 break 就會從上穿到底的狀況。再例如 implicitly unwrapped optionals ,隱式解析可選類型,則是默認會進行解包操做不用手動經過 ! 進行解包。ios

回到 switch 的問題,看下下面這段代碼:git

let anotherCharacter: Character = "a"

switch anotherCharacter {
case "a":
    println("The letter a")
case "A":
    println("The letter A")
default:
    println("Not the letter A")
}

能夠看到雖然匹配到了 case "a" 的狀況,可是在當前 case 結束以後便直接跳出,沒有繼續往下執行。若是想繼續貫穿到下面的 case 能夠經過 fallthrough 實現。swift

Tuple

咱們能夠在 switch 中使用元祖 (tuple) 進行匹配。用 _ 表示全部值。好比下面這個例子,判斷座標屬於什麼區域:app

let somePoint = (1, 1)

switch somePoint {
case (0, 0):    // 位於遠點
    println("(0, 0) is at the origin")
case (_, 0):    // x爲任意值,y爲0,即在 X 軸上
    println("(\(somePoint.0), 0) is on the x-axis")
case (0, _):    // y爲任意值,x爲0,即在 Y 軸上
    println("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):  // 在以原點爲中心,邊長爲4的正方形內。
    println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
    println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}

// "(1, 1) is inside the box"

若是想在 case 中用這個值,那麼能夠用過值綁定 (value bindings) 解決:ide

let somePoint = (0, 1)

switch somePoint {
case (0, 0):
    println("(0, 0) is at the origin")
case (let x, 0):
    println("x is \(x)")
case (0, let y):
    println("y is \(y)")
default:
    println("default")
}

Where

case 中能夠經過 where 對參數進行匹配。好比咱們想打印 y=x 或者 y=-x這種45度仰望的狀況,之前是經過 if 解決,如今能夠用 switch 搞起:函數

let yetAnotherPoint = (1, -1)

switch yetAnotherPoint {
case let (x, y) where x == y:
    println("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
    println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
    println("(\(x), \(y)) is just some arbitrary point")
}
// "(1, -1) is on the line x == -y」

Control Transfer Statements

Swift 有四個控制轉移狀態:oop

  • continue - 針對 loop ,直接進行下一次循環迭代。告訴循環體:我此次循環已經結束了。
  • break - 針對 control flow (loop + switch),直接結束整個控制流。在 loop 中會跳出當前 loop ,在 switch 中是跳出當前 switch 。若是 switch 中某個 case 你實在不想進行任何處理,你能夠直接在裏面加上 break 來忽略。
  • fallthrough - 在 switch 中,將代碼引至下一個 case 而不是默認的跳出 switch。
  • return - 函數中使用

其餘

看到一個有趣的東西:Swift Cheat Sheet,裏面是純粹的代碼片斷,若是忽然短路忘了語法能夠來看看。ui

好比 Control Flow 部分,有以下代碼,基本覆蓋了全部的點:翻譯

// for loop (array)
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
    if value == 1 {
        println("One!")
    } else {
        println("Not one!")
    }
}

// for loop (dictionary)
var dict = [
    "name": "Steve Jobs",
    "title": "CEO",
    "company": "Apple"
]
for (key, value) in dict {
    println("\(key): \(value)")
}

// for loop (range)
for i in -1...1 { // [-1, 0, 1]
    println(i)
}
// use .. to exclude the last number

// for loop (ignoring the current value of the range on each iteration of the loop)
for _ in 1...3 {
    // Do something three times.
}

// while loop
var i = 1
while i < 1000 {
    i *= 2
}

// do-while loop
do {
    println("hello")
} while 1 == 2

// Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
    let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
    let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
    let vegetableComment = "Is it a spicy \(x)?"
default: // required (in order to cover all possible input)
    let vegetableComment = "Everything tastes good in soup."
}

// Switch to validate plist content
let city:Dictionary<String, AnyObject> = [
    "name" : "Qingdao",
    "population" : 2_721_000,
    "abbr" : "QD"
]
switch (city["name"], city["population"], city["abbr"]) {
    case (.Some(let cityName as NSString),
        .Some(let pop as NSNumber),
        .Some(let abbr as NSString))
    where abbr.length == 2:
        println("City Name: \(cityName) | Abbr.:\(abbr) Population: \(pop)")
    default:
        println("Not a valid city")
}

References

相關文章
相關標籤/搜索