Swift控制流

Swift提供了多种流程控制结构,包括可以多次执行任务的while循环,基于特定条件选择执行不同代码分支的if、guard和switch语句,还有控制流程跳转到其他代码的break和continue语句。

Swift 还增加了for-in循环,用来更简单地遍历数组(array),字典(dictionary),区间(range),字符串(string)和其他序列类型。

For-In循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
for index in 1...5 {
print("\(index) times is \(index * 5)")
}

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)")
}

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName) has \(legCount) legs")
}

While循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//While循环
let finalSquare = 25
var board = [Int](count: finalSquare + 1, repeatedValue: 0)

board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08

var square = 0
var diceRoll = 0
while square < finalSquare {
//掷骰子
diceRoll += 1
if diceRoll > 6 {
diceRoll = 1
}
//根据点数移动
square += diceRoll

if square < board.count {
//如果玩家还在棋盘上,顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
}
}
print("Game Over")

//Repeat-While
square = 0
diceRoll = 0

repeat {
//如果玩家还在棋盘上,顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
diceRoll += 1
//掷骰子
if diceRoll > 6 {
diceRoll = 1
}
//根据点数移动
square += diceRoll
} while square < finalSquare

条件语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//If
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}

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.")
}

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.")
}

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.")
}

//Switch
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 anotherCharacter: Character = "a"
switch anotherCharacter {
// case "a": //会报错:case "a": does not contain any executable statements
case "A":
print("The letter A")
default:
print("Not the letter A")
}

//区间匹配
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var 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).")

//元组
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("(0, 0) is at the origin")
case (_, 0):
print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
print("(0, \(somePoint.1) is on the y-axis)")
case (-2...2, -2...2):
print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
print("((\(somePoint.0), \(somePoint.1)) is outside the box)")
}

//值绑定
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)") // 输出 "on the x-axis with an x value of 2"
case (0, let y):
print("ont the y-axis with a y value of \(y)")
case (let x, let y):
print("somewhere else at (\(x), \(y))")
}

//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") // 输出 "on the x-axis with an x value of 2"
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}

控制转移语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//continue
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default:
puzzleOutput.append(character)
}
}
print("\(puzzleOutput)") //输出 "grtmndsthnklk"

//-break
//循环体中的break
//当在一个循环体中使用break时,会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(})后的第一行代码。不会再有本次循环迭代的代码被执行,也不会再有下次的循环迭代产生。
//switch语句中的break
//当在一个switch代码块中使用break时,会立即中断该switch代码块的执行,并且跳转到表示switch代码块结束的大括号(})后的第一行代码。
let numberSymbol: Character = "三"
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
possibleIntegerValue = 1
case "2", "٢", "二", "๒":
possibleIntegerValue = 2
case "3", "٣", "三", "๓":
possibleIntegerValue = 3
// break
case "4", "٤", "四", "๔":
possibleIntegerValue = 4
default:
break
}
if let integerValue = possibleIntegerValue {
print("The integer value of \(numberSymbol) is \(integerValue)")
} else {
print("An integer value could not be found for \(numberSymbol)")
}
//-fallthrough 贯穿
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough //只会贯穿到下一条case,而不是贯穿整个switch
case 0:
description += " an integer."
default:
description += " too."
}
print(description) //输出:The number 5 isa prime number, and also an integer.

//带标签的语句
square = 0
diceRoll = 0
gameLoop: while square != finalSquare {
if ++diceRoll == 7 {
diceRoll = 1
}
switch square + diceRoll {
case finalSquare:
//到达最后一个方块, 游戏结束
break gameLoop
case let newSquare where newSquare > finalSquare:
//超出最后一个方块,宰只一次骰子
continue gameLoop
default:
//本次移动有效
square += diceRoll
}
}
print("Game over!")

//提前退出
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(["name":"John"])
greet(["name":"Jane","location":"Cupertino"])

检测API可用性

1
2
3
4
5
if #available(iOS 9, OSX 10.10, *) {
//在 iOS 使用 iOS9 的API,在 OS X 使用 OS X v10.10 的 API
} else {
//使用先前版本的 iOS 和 OS X 的 API
}

本文原地址

–EOF–