Swift4学习

Swift4-控制流

2018-08-09  本文已影响15人  wingsrao

控制流

1.stride(from:to:by:)和stride(from:through:by:)

2.要在特定的 switch 情况中使用贯穿行为,使用 fallthrough 关键字。

3.你可以使用元组来在一个 switch 语句中测试多个值。每个元组中的元素都可以与不同的值或者区间进行匹配。另外,使用下划线( _)来表明匹配所有可能的值。

4.值绑定:

let anotherPoint = (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))")
}
// prints "on the x-axis with an x value of 2"

注意这个 switch 语句没有任何的 default 情况。最后的情况, case let (x,y) ,声明了一个带有两个占位符常量的元组,它可以匹配所有的值。结果,它匹配了所有剩下的值,然后就不需要 default 情况来让 switch 语句穷尽了。

5.switch 情况可以使用 where 分句来检查额外的情况。

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

6.Fallthrough:switch中使用fallthrough 关键字来“贯穿到” default 情况。

7.标签 continue和break labelName

8.提前退出:guard 语句,类似于 if 语句,基于布尔值表达式来执行语句。使用 guard 语句来要求一个条件必须是真才能执行 guard 之后的语句。与 if 语句不同, guard 语句总是有一个 else 分句—— else 分句里的代码会在条件不为真的时候执行。

guard let name = person["name"] else {
    return
}

9.检查API的可用性

if #available(iOS 10, macOS 10.12, *) {
    // Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
} else {
    // Fall back to earlier iOS and macOS APIs
}
上一篇下一篇

猜你喜欢

热点阅读