For-In 循环
输出乘 5 乘法表前面一部分内容:
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"
使用 for-in 遍历一个数组所有元素:
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, (name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
在 for-in 循环中使用显式的常量名称来解读 (key, value) 元组
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("(animalName)s have (legCount) legs")
}
// ants have 6 legs
// cats have 4 legs
// spiders have 8 legs
While 循环
while 循环的一般格式:
while condition {
statements
}
repeat-while 循环的一般格式:
repeat {
statements
} while condition
条件语句
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."
Switch
switch some value to consider {
case value 1:
respond to value 1
case value 2,
value 3:
respond to value 2 or 3
default:
otherwise, do something else
}
每一个 case 分支都必须包含至少一条语句。
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"
控制转移语句
Swift 有五种控制转移语句:
- 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"
- break: break 语句会立刻结束整个控制流的执行。当你想要更早的结束一个 switch 代码块或者一个循环体时,你都可以 使用 break 语句。
let numberSymbol: Character = "三" // 简体中文里的数字 3 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).")
}
// 输出 "The integer value of 三 is 3."
- fallthrough: Swift 中的 switch 不会从上一个 case 分支落入到下一个 case 分支中,如果你确实需要 C 风格的贯穿的特性,你可以在每个需要该特性的 case 分支中使用 fallthrough 关键字。
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."
- return
- throw
提前退出
像 if 语句一样, guard 的执行取决于一个表达式的布尔值。
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"])
// 输出 "Hello John!"
// 输出 "I hope the weather is nice near you." greet(["name": "Jane", "location": "Cupertino"]) // 输出 "Hello Jane!"
// 输出 "I hope the weather is nice in Cupertino."
如果 guard 语句的条件被满足,则继续执行 guard 语句大括号后的代码。将变量或者常量的可选绑定作为guard语句的条件,都可以保护 guard 语句后面的代码。
如果条件不被满足,在 else 分支上的代码就会被执行。
检测 API 可用性
在 if 或 guard 语句中使用 可用性条件(availability condition) 去有条件的执行一段代码,来在运行时判 断调用的API是否可用。编译器使用从可用性条件语句中获取的信息去验证,在这个代码块中调用的 API 是否可 用。
if #available(iOS 10, macOS 10.12, *) {
// 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
} else {
// 使用先前版本的 iOS 和 macOS 的 API
}
网友评论