Swift4-控制流

作者: wingsrao | 来源:发表于2018-08-09 10:54 被阅读15次

控制流

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
}

相关文章

  • Swift4-控制流

    控制流 1.stride(from:to:by:)和stride(from:through:by:) 2.要在特定...

  • 9.控制流(theControlFlow)

    控制流 kotlin_控制流 swift控制流

  • Python | 常用的控制流语句

    一、控制流语句介绍 了解什么是控制流语句以及Python常用的两种控制流语句。 1.控制流语句 控制流语句即用来实...

  • 控制流

    上一篇:基础运算当前篇:控制流下一篇:集合类型 从大体来讲控制流分为条件语句和循环语句,而这两种语句差不多就是程序...

  • 控制流

    0. 分支结构 概念:指程序的 流程走向,比较像一棵树 分散 的 树枝 分类单分支判断1. 一般形式 age ...

  • 控制流

    控制流 [TOC] Swift提供了多种流程控制结构,包括可以多次执行任务的while循环,基于特定条件选择执行不...

  • 控制流

    语句与程序块 在表达式之后加上一个分号(;),它们就变成了语句。例如: 在C语言中,分号是语句的结束符。用一对花括...

  • 控制流

    foreach bind 1.示例 2.不带元素的绑定 if bind 1.绑定示例 if 绑定是很重要的,它能让...

  • 控制流

    For循环 for循环用来按照指定的次数多次执行一系列语句。Swift 提供两种for循环形式: for-in用来...

  • 控制流

    For-In 循环 输出乘 5 乘法表前面一部分内容: 如果你不需要区间序列内每一项的值,你可以使用下划线( _ ...

网友评论

    本文标题:Swift4-控制流

    本文链接:https://www.haomeiwen.com/subject/slsqbftx.html