条件语句
(1) 只包含一个条件语句:
if 判断条件 {
语句
}
(2) 包含两个条件语句:
if 判断条件 {
语句 1
} else {
语句 2
}
(3) 包含多个条件语句:
if 判断条件 {
语句 1
} else if 判断条件 {
语句 2
} else if 判断条件 {
语句 3
}
...
else if 判断条件 {
语句 m
} else {
语句 n
}
1. 必须显式地指明具体的判断条件是 true 还是 false;
2. if 语句条件的 () 可以省略,但 {} 不能省略;
3. 当最后没任务执行的情况下,else if 中的最后的 else 可以省略。
if-let 语句
语法格式:
if let 常量名 = 可选变量名 {
语句
}
let oAge: Int? = 20
if let age = oAge, age > 18 {
print(age)
}
guard 判断条件 else {
语句 1
return
}
语句组
1. 当判断条件为 true 的时候,跳过 else 语句的内容,直接执行语句组;
2. 当判断条件为 false 的时候,执行 else 语句的内容,其跳转语句一般为 return, break, continue,
和 throw;
3. guard 在函数里面使用。
guard-let 语句
语法格式:
guard let 常量名 = 可选变量名 ... else {
语句 1
return
}
语句组
func guardCase() {
let oAge: Int? = 20
guard let age = oAge, age > 18 else {
print("年龄小于 18 岁")
return
}
print(age)
}
- switch 语句:通过和具体的值匹配去执行相应的代码。
语法格式:
switch (表达式) {
case 常量表达式 1:
语句 1
case 常量表达式 2:
语句 2
...
case 常量表达式 n:
语句 n
default:
语句 n + 1
}
let rank = "A"
switch rank {
case "A", "B":
print("优")
case "C":
print("差")
default:
print("没有评定级别")
}
let rank = "A"
switch rank {
case "A":
var number = 10
print("优")
case "B":
print("良")
case "C":
print("差")
default:
print("没有评级")
}
let m = 3.14
switch m {
case 3.14:
print("π")
default:
print("not π")
}
let nameString = "why"
switch nameString {
case "why":
print("英语老师")
case "wxx":
print("体育老师")
default:
print("其他老师")
}
let number = 20
switch number {
case 1...9:
print("个位数")
case 10...99:
print("十位数")
default:
print("其它数")
}
let coordinate = (0, 0)
switch coordinate {
case (1, 0):
print("原点")
case (_, 0):
print("x轴")
case (0, _):
print("y轴")
case (-2...2, -2...2):
print("矩形区域")
default:
print("没有任何目标区域")
}
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 an y value of \(y)")
case (let x, let y):
print("somewhere else at (\(x), \(y))")
}
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")
}
let numberSymbol: Character = "三"
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "?", "一":
possibleIntegerValue = 1
case "2", "?", "二":
possibleIntegerValue = 2
case "3", "?", "三":
possibleIntegerValue = 3
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).")
}
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)
循环语句
应用场景:用来遍历一个集合中的所有元素。
语法格式:
for index in collection {
}
for i in 1...5 {
print(i)
}
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)s have \(letCount) legs")
}
var j = 0
for j in 2...6 {
print(j)
}
print(j)
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
1. index 是一个每次循环遍历开始时被自动赋值的常量,无需使用 let 关键字声明;
2. index 常量只存在于循环的生命周期里,如果要扩大作用域,必须在循环之前进行常量或者变量声明。
语法格式:
while 循环条件 {
}
若判断条件为 true ,则执行 while 循环中的代码块,否则跳出 while 循环
蛇与梯子游戏,示例代码:
let finalSquare = 25
var board = [Int](repeating: 0, count: finalSquare + 1)
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
while square < finalSquare {
let diceRoll = Int(arc4random() % 6) + 1
print(diceRoll)
square += diceRoll
if square < board.count {
square += board[square]
}
}
print("Game over!")
死循环是无法靠自身控制终止的循环,一般写法:
while true {
statement(s)
}
repeat-while 循环
语法格式:
repeat {
} while condition
* 先执行一次循环的代码;
** 重复循环直到条件为 false。
蛇和梯子游戏改写,示例代码:
let finalSquare = 25
var board = [Int](repeating: 0, count: finalSquare + 1)
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
repeat {
square += board[square]
let diceRoll = Int(arc4random() % 6) + 1
print(diceRoll)
square += diceRoll
} while square < finalSquare
print("Game over!")
控制转移语句
- 定义:改变代码的执行顺序,通过它可以实现代码的跳转。
- 分类:return、break、continue、throw、fallthrough。
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)
break:会立刻结束整个控制流的执行。
1. 循环语句中 break:
(1) 当在一个循环体中使用 break 时;
(2) 会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(})后的第一行代码;
(3) 不会再有本次循环的代码被执行,也不会再有下次的循环产生。
2. switch 语句中的 break:
(1) 当在一个 switch 代码块中使用 break 时;
(2) 会立即中断该 switch 代码块的执行;
(3) 并且跳转到表示 switch 代码块结束的大括号(})后的第一行代码。
带标签的语句
- 应用场景:在循环体和条件语句中嵌套循环体和条件语句来创造复杂的控制流结构。
label name: while condition { statements }
示例代码:
let finalSquare = 25
var board = [Int](repeating: 0, count: finalSquare + 1)
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
gameLoop: while square != finalSquare {
diceRoll = Int(arc4random() % 6) + 1
print(diceRoll)
switch square + diceRoll {
case finalSquare:
break gameLoop
case let newSquare where newSquare > finalSquare:
continue gameLoop
default:
square += diceRoll
square += board[square]
}
}
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(person: ["name": "John"])
greet(person: ["name": "Jane", "location": "Cupertino"])
检测 API 可用性
语法格式:
if #available(platform name version, ... , *) {
} else {
}
示例代码:
if #available(iOS 10, macOS 10.12, *) {
} else {
}