Swift-控制流

1. For in 循环

遍历一个集合中的所有元素。 例如:数组中的元素、范围内的数字或者字符串中的字符。

  • 遍历一个数组所有元素:
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
  • 遍历一个字典来访问它的键值对:
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
// cats have 4 legs
// ants have 6 legs
// spiders have 8 legs
  • 遍历数字范围
for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
  • 不需要区间序列内一项的值,你可以使用下划线(_)替代变量名来忽略这个值:
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")  // 输出“3 to the power of 10 is 59049”
  • 使用半开区间运算符(..<)来表示一个左闭右开的区间:
let minutes = 60
for tickMark in 0..<minutes {
    // 每一分钟都渲染一个刻度线(60次)
}
  • 可以每 5 分钟作为一个刻度。使用 stride(from:to:by:) 函数跳过不需要的标记:
let minuteInterval = 5
let minutes = 60
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
    // 每5分钟渲染一个刻度线(0, 5, 10, 15 ... 45, 50, 55)
}
  • 在闭区间使用 stride(from:through:by:) 起到同样作用:
let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
    // 每3小时渲染一个刻度线(3, 6, 9, 12)
}

2. While 循环

while 循环会一直运行一段语句直到条件变成 false。Swift 提供两种 while 循环形式:

  • while 循环,每次在循环开始时计算条件是否符合。
  • repeat-while 循环,每次在循环结束时计算条件是否符合。

2.1 While

  • while 循环从计算一个条件开始。如果条件为 true,会重复运行一段语句,直到条件变为 false。
  • while 循环的一般格式:
while condition {
    statements
}

2.2 Repeat-While

  • 判断循环条件之前,先执行一次循环的代码块。然后重复循环直到条件为 false。
  • repeat-while 循环的一般格式:
repeat {
    statements
} while condition

3. 条件语句

3.1 if

  • 该条件为 true 时,才执行相关代码:
temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}   // 输出“It's not that cold. Wear a t-shirt.”
  • 可以把多个 if 语句链接在一起,来实现更多分支:
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}   // 输出“It's really warm. Don't forget to wear sunscreen.”
  • 不需要完整判断情况的时候,最后的 else 语句是可选的:
temperatureInFahrenheit = 72
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
}

3.2 Switch

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

3.2.1 不存在隐式的贯穿

与 C 和 Objective-C 中的 switch 语句不同,在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止 switch 语句,而不会继续执行下一个 case 分支。

  • 把某个值与一个或若干个相同类型的值作比较:
let someCharacter: Character = "z"
switch someCharacter {
case "a":
    print("The first letter of the alphabet")
case "z":
    print("The last letter of the alphabet")
default:
    print("Some other character")
}   // 输出“The last letter of the alphabet”
  1. Swift 中 break 不是必须的。
  2. 在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止 switch 语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用 break 语句。
  • 每一个 case 分支都必须包含至少一条语句:
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // 无效,这个分支下面没有语句
case "A":
    print("The letter A")
default:
    print("Not the letter A")
}   
!!!这段代码会报编译错误
  • 让单个 case 同时匹配 a 和 A,可以将这个两个值组合成一个复合匹配,并且用逗号分开:
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
    print("The letter A")
default:
    print("Not the letter A")
}   // 输出“The letter A”

3.2.2 区间匹配

  • case 分支的模式也可以是一个值的区间
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")    // 输出“There are dozens of moons orbiting Saturn.”

3.2.3 元组匹配

  • 可以使用元组在同一个 switch 语句中测试多个值。
  • 元组中的元素可以是值,也可以是区间。
  • 使用下划线(_)来匹配所有可能的值。
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("\(somePoint) is at the origin")
case (_, 0):
    print("\(somePoint) is on the x-axis")
case (0, _):
    print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
    print("\(somePoint) is inside the box")
default:
    print("\(somePoint) is outside of the box")
}   // 输出“(1, 1) is inside the box”

Swift 允许多个 case 匹配同一个值。
在这个例子中,点 (0, 0)可以匹配所有四个 case。
如果存在多个匹配,那么只会执行第一个被匹配到的 case 分支。
点 (0, 0)会首先匹配 case (0, 0),因此剩下的能够匹配的分支都会被忽视掉。

3.2.4 值绑定(Value Bindings)

case 分支允许将匹配的值声明为临时常量或变量,并且在 case 分支体内使用 —— 这种行为被称为值绑定(value binding),因为匹配的值在 case 分支体内,与临时的常量或变量绑定。

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))")
}   // 输出“on the x-axis with an x value of 2”
注意:
    这个 switch 语句不包含默认分支。这是因为最后一个 case ——case let(x, y) 声明了一个可以匹配余下所有值的元组。这使得 switch 语句已经完备了,因此不需要再书写默认分支。

3.2.5 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")
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")
}   // 输出“(1, -1) is on the line x == -y”

3.2.6 复合型 Cases

  • 当多个条件可以使用同一种方法来处理时,可以将这几种可能放在同一个 case 后面,并且用逗号隔开。当 case 后面的任意一种模式匹配的时候,这条分支就会被匹配。并且,如果匹配列表过长,还可以分行书写:
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
     "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    print("\(someCharacter) is a consonant")
default:
    print("\(someCharacter) is not a vowel or a consonant")
}   // 输出“e is a vowel”
  • 复合匹配同样可以包含值绑定。复合匹配里所有的匹配模式,都必须包含相同的值绑定。并且每一个绑定都必须获取到相同类型的值。 这保证了,无论复合匹配中的哪个模式发生了匹配,分支体内的代码,都能获取到绑定的值,并且绑定的值都有一样的类型。
let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
    print("On an axis, \(distance) from the origin")
default:
    print("Not on an axis")
}   // 输出“On an axis, 9 from the origin”

上面的 case 有两个模式:

  1. (let distance, 0) 匹配了在 x 轴上的值,
  2. (0, let distance) 匹配了在 y 轴上的值。

两个模式都绑定了 distance,并且 distance 在两种模式下,都是整型——这意味着分支体内的代码,只要 case 匹配,都可以获取到 distance 值。

4. 控制转移语句

控制转移语句改变你代码的执行顺序,通过它可以实现代码的跳转。

4.1Swift 有五种控制转移语句:

  • continue:告诉一个循环体立刻停止本次循环,重新开始下次循环。
  • break:break 语句会立刻结束整个控制流的执行。break 可以在 switch 或循环语句中使用,用来提前结束 switch 或循环语句。
  • fallthrough:贯穿(Fallthrough)从上一个 case 分支跳转到下一个 case 分支中。
  • return:返回
  • throw:错误抛出
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
    description += " a prime number, and also"
    fallthrough
default:
    description += " an integer."
}
print(description)  // 输出“The number 5 is a prime number, and also an integer.”

4.2 带标签的语句

标签(statement label):标记一个循环体或者条件语句。

  • 对于一个条件语句,你可以使用 break 加标签的方式,来结束这个被标记的语句。
  • 对于一个循环语句,你可以使用 break 或者 continue 加标签,来结束或者继续这条被标记语句的执行。
  • 针对 while 循环体的标签语法,同样的规则适用于所有的循环体和条件语句:
label name: while condition {
     statements
 }

4.3 提前退出

  • 使用 guard 语句来要求条件必须为真时,以执行 guard 语句后的代码。
  • 不同于 if 语句,一个 guard 语句总是有一个 else 从句,如果条件不为真则执行 else 从句中的代码。
func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }
​
    print("Hello \(name)!")
​
    guard let location = person["location"] else {
        print("I hope the weather is nice near you.")
        return
    }
​
    print("I hope the weather is nice in \(location).")
}
​
greet(person: ["name": "John"])
// 输出“Hello John!”
// 输出“I hope the weather is nice near you.”
greet(person: ["name": "Jane", "location": "Cupertino"])
// 输出“Hello Jane!”
// 输出“I hope the weather is nice in Cupertino.”
注意:
    1.如果条件不被满足,在 else 分支上的代码就会被执行。
    2.这个分支必须转移控制以退出 guard 语句出现的代码段。
    3.可以用控制转移语句如 return、break、continue 或者 throw 做这件事,或者调用一个不返回的方法或函数,例如 fatalError()。

相比于可以实现同样功能的 if 语句,按需使用 guard 语句会提升我们代码的可读性。它可以使你的代码连贯的被执行而不需要将它包在 else 块中,它可以使你在紧邻条件判断的地方,处理违规的情况。

4.4 检测 API 可用性

  • Swift 内置支持检查 API 可用性,这可以确保我们不会在当前部署机器上,不小心地使用了不可用的 API。
  • 编译器使用 SDK 中的可用信息来验证我们的代码中使用的所有 API 在项目指定的部署目标上是否可用。如果我们尝试使用一个不可用的 API,Swift 会在编译时报错。
if #available(iOS 10, macOS 10.12, *) {
    // 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
} else {
    // 使用先前版本的 iOS 和 macOS 的 API
}
  • 平台名字可以是:iOS,macOS,watchOS 和 tvOS
if #available(平台名称 版本号, ..., *) {
    APIs 可用,语句将执行
} else {
    APIs 不可用,语句将不执行
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • Swift 提供了类似 C 语言的流程控制结构,包括可以多次执行任务的for和while循环,基于特定条件选择执行...
    穷人家的孩纸阅读 688评论 1 1
  • Swift提供了多种控制流声明。包括while循环来多次执行一个任务;if,guard和switch声明来根据确定...
    BoomLee阅读 1,924评论 0 3
  • Swift提供了多种流程控制结构,包括可以多次执行任务的while循环,基于特定条件选择执行不同代码分支的if、g...
    CDLOG阅读 705评论 0 1
  • Swift提供了各种控制流语句。 这些包括while循环来执行多次任务; if,guard和switch语句,以根...
    Joker_King阅读 414评论 0 0
  • Swift提供了多种流程控制结构,包括可以多次执行任务的while循环,基于特定条件基于特定条件选择执行不同代码分...
    edison0428阅读 1,200评论 0 0