您的位置:首页 > 其它

5控制流

2016-02-18 14:16 232 查看
控制流:

1.for 循环

for index in 1...5{

}
index的每次遍历开始时被自动赋值的常量,所以不用let关键字.

for _ in 1...5{

}
_能忽略具体的值.


2.while

while
repeat-while 和 do - while 类似.


3.switch

switch some value to consider {
case value 1:// 单个匹配
respond to value 1
case value 2, value 3: // 多个匹配用 , 分割
respond to value 2 or 3
default:
otherwise, do something else
}


switch 中不带break,自动终止.switch 的每条 case 语句都必须有执行语句,否则出错.

switch 有区间匹配,其实就是多个匹配.

let a = 2
switch a {
case 1...5:         // 区间的匹配
print("1...5")
case 6:             // 单个值得匹配
print("6")
case 8,9:           // 多个值得匹配
print("8或者9")
case (0,0):         // 元组的匹配
print("元组0,0")
case (_,0):         // _可以匹配所有可能的值
print("小于0的值")
case (-2...2,-2...2):   // 元组区间的匹配
print("元组中区间的匹配")
default:
print("没有匹配的对象")
}


1.值绑定:

case 分支的模式允许将匹配的值绑定到一临时的常量或变量,这些常量或变量就可以在 case 语句中使用。

let somePoint = (1,1);
switch somePoint{
case (let x,0):
print("on the x-axis with an x value of \(x)");
case let(x,y):
print("somewhere else at (\(x),\(y))")
}


2.where

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

let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
}


3.控制转移语句

continue: 结束本次循环,开始下一次的循环
break: 终止本次循环
switch 中的 break,swift 中的 switch 的 break 和 OC 中的 break,不一样
fallthrough: 贯穿
swift 中的 switch  中的 case 执行完是终止的,想要实现 OC 中的不带 break 的功能就必须贯穿,fallthrough.


4.提前退出

guard 条件语句 else{
控制转移语句 // 条件为false 执行,这个分支必须转移控制以退出 guard 语句出现的代码段
}
语句 // 条件为真时,执行


5.检测API 是否可用

if #available(`platform name` `version`, `...`, *) {
`statements to execute if the APIs are available`
} else {
`fallback statements to execute if the APIs are unavailable`
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: