1. For-In循环
for-in循环中如果我们不需要知道每一次循环中计数器具体的值,用下划线_替代循环中的变量,能够忽略当前值。
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
2. While循环
while循环在这里忽略讲解,主要说说while循环的另一种形式repeat-while,它和while的区别是在判断循环条件之前,先执行一次循环代码块,然后重复循环直到条件为false,类似于其他语言中的do-while。
3. 条件语句
Swift提供两种类型的条件语句:If语句和switch语句。
switch语句不需要再case分支中显式地使用break,不存在隐式贯穿,每个case分支都必须包含至少一条语句。
单个case语句可以复合匹配和区间匹配。
4. 元组
略。
5. 值绑定
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))")
}
6. 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")
}
7. 复合匹配
当多个条件可以使用同一种方法来处理时,可以将这几种可能放在同一个case后面,并且用逗号隔开。
8. 控制转移语句
8.1 Continue
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"
8.2 Break
break语句会立刻结束整个循环体的执行。
8.3 贯穿
Swift中的switch不会从上一个case分支落入到下一个case分支中。如果你需要C风格的贯穿特性,可以在每个需要该特性的case分支中使用fallthrough关键字。
let integerToDescirbe = 5
var description = "The number \(integerToDescirbe) is"
switch integerToDescirbe {
case 2, 3, 5, 6, 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."
8.4 提前退出
条件为真时,执行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."
8.5 检测API可用性
if #available(iOS 10, macOS 10.12, *) {
// 在iOS使用iOS 10的API,在macOS使用macOS 10.12的API
} else {
// 使用先前版本的iOS和macOS的API
}
平台名字可以是iOS,macOS,watchOS和tvOS。