@evolxb
2015-05-20T12:27:45.000000Z
字数 1365
阅读 1112
swift 控制流
for-in循环for-condition-increment循环for-in循环for-in用了遍历一个区间(range),序列(sequence),集合(collection),系列(progression)里面所有的元素执行一系列语句。
(for-condition-increment)do-while循环switch 语句会尝试把某个值与若干个模式(pattern)进行匹配。
let count = 3_000_000_000_000let countedThings = "stars in the Milky Way"var naturalCount : Stringswitch count {case 0 : naturalCount = "no"case 1...3 : naturalCount = "a few"case 4...9 : naturalCount = "several"case 10...99 : naturalCount = "tens of"case 100...999 : naturalCount = "hundreds of"case 1000...999_999 : naturalCount = "thousands of"default : naturalCount = "default case"}
let somePoint = (1, 1)switch somePoint {case (0, 0) : println("origin point.")case (_, 0) : println("x-axis")case (0, _) : println("y-axis")case (-2...2, -2...2) : println("inside a box")default : println("some point")}
_ 匹配所有可能的值。
case 分支的模式允许将匹配的值绑定到一个临时的常量或者变量,这些常量或者变量在该 case 分支就可以被引用了。
let anotherPoint = (2, 0)switch anotherPoint {case (let x, 0) :println("on the x-axis with x value of \(x)")case (0, let y) :println("on the y-axis with y value of \(y)")case let (x, y) :println("somewhere else at (\(x), \(y))")}
case 分支的模式可以使用 where 语句来判断额外的条件。
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("somewhere point .")}