[关闭]
@evolxb 2015-05-20T20:27:45.000000Z 字数 1365 阅读 986

swift 控制流

swift 控制流


For 循环

for-in循环

for-in用了遍历一个区间(range),序列(sequence),集合(collection),系列(progression)里面所有的元素执行一系列语句。

for条件递增(for-condition-increment)

while 循环

条件语句

switch 语句

switch 语句会尝试把某个值与若干个模式(pattern)进行匹配。

switch 区间匹配

  1. let count = 3_000_000_000_000
  2. let countedThings = "stars in the Milky Way"
  3. var naturalCount : String
  4. switch count {
  5. case 0 : naturalCount = "no"
  6. case 1...3 : naturalCount = "a few"
  7. case 4...9 : naturalCount = "several"
  8. case 10...99 : naturalCount = "tens of"
  9. case 100...999 : naturalCount = "hundreds of"
  10. case 1000...999_999 : naturalCount = "thousands of"
  11. default : naturalCount = "default case"
  12. }

元组(tuple)

  1. let somePoint = (1, 1)
  2. switch somePoint {
  3. case (0, 0) : println("origin point.")
  4. case (_, 0) : println("x-axis")
  5. case (0, _) : println("y-axis")
  6. case (-2...2, -2...2) : println("inside a box")
  7. default : println("some point")
  8. }

_ 匹配所有可能的值。

值绑定(Value Bindings)

case 分支的模式允许将匹配的值绑定到一个临时的常量或者变量,这些常量或者变量在该 case 分支就可以被引用了。

  1. let anotherPoint = (2, 0)
  2. switch anotherPoint {
  3. case (let x, 0) :
  4. println("on the x-axis with x value of \(x)")
  5. case (0, let y) :
  6. println("on the y-axis with y value of \(y)")
  7. case let (x, y) :
  8. println("somewhere else at (\(x), \(y))")
  9. }

Where

case 分支的模式可以使用 where 语句来判断额外的条件。

  1. let yetAnotherPoint = (1, -1)
  2. switch yetAnotherPoint {
  3. case let (x, y) where x == y :
  4. println("(\(x), \(y)) is on the line x == y")
  5. case let (x, y) where x == -y :
  6. println("(\(x), \(y)) is on the line x == -y")
  7. case let (x, y) :
  8. println("somewhere point .")
  9. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注