控制流
Swift包含很多控制流語句:while循環(huán)、if炎疆、guard、switch和for-in循環(huán)国裳。
<br />
For-In循環(huán)
for-in循環(huán)用于迭代序列形入,如數(shù)組遍歷、數(shù)字范圍缝左、字符串中的字符亿遂。
下面為for-in循環(huán)遍歷數(shù)組:
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")
}
// ants have 6 legs
// spiders have 8 legs
// cats have 4 legs
遍歷數(shù)字范圍:
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
若不需要序列中的值時(shí)浓若,使用下劃線代替變量名來忽略這些值:
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
遍歷半開數(shù)字范圍:
let minutes = 60
for tickMark in 0..<minutes {
// render the tick mark each minute (60 times)
}
使用stride(from:to:by:)方法跳過不需要的遍歷:
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
// render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}
stride(from:through:by:)方法遍歷包括結(jié)尾值:
let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
// render the tick mark every 3 hours (3, 6, 9, 12)
}
<br />
While循環(huán)
Swift有兩種while循環(huán):
- 每次循環(huán)開始時(shí)判斷循環(huán)條件的while循環(huán)
- 每次循環(huán)結(jié)束時(shí)判斷循環(huán)條件的repeat-while循環(huán)
While
while循環(huán)語法:
while condition {
statements
}
Repeat-While
Swift的repeat-while循環(huán)與其他語言的do-while循環(huán)類似。
repeat-while循環(huán)語法:
repeat {
statements
} while condition
<br />
條件語句
Swift提供兩種條件語句:if和switch語句蛇数。if判斷簡單條件挪钓,可能結(jié)果較少;switch適合復(fù)雜條件且可能情況較多的情況耳舅,常用于模式匹配碌上。
If
Swift中的if語句可忽略判斷條件的括號(hào),但執(zhí)行語句的大括號(hào)不可或缺:
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}
// Prints "It's very cold. Consider wearing a scarf."
if-else語句:
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.")
}
多重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.")
}
Switch
switch語句比較多個(gè)匹配模式浦徊,且能匹配任意類型值馏予,語法如下:
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
}
switch語句必須列出所有可能情況。
下面例子匹配單個(gè)小寫字符:
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")
}
Swift的switch語句不需要在每個(gè)語句塊最后顯式使用break語句(也可使用)盔性。當(dāng)匹配某個(gè)條件時(shí)霞丧,之間結(jié)束執(zhí)行整個(gè)switch語句。
switch語句的每個(gè)條件必須只要包含一個(gè)可執(zhí)行語句冕香,否則會(huì)拋出編譯錯(cuò)誤:
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // Invalid, the case has an empty body
case "A":
print("The letter A")
default:
print("Not the letter A")
}
// This will report a compile-time error.
要將兩個(gè)判斷條件合并蛹尝,使用逗號(hào)隔開:
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
print("The letter A")
default:
print("Not the letter A")
}
注意
要想顯示跳過某次判斷條件,進(jìn)入下個(gè)條件悉尾,使用fallthrough關(guān)鍵字突那。
間隔匹配
使用間隔匹配可在一條判斷語句中匹配多個(gè)值:
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).")
// Prints "There are dozens of moons orbiting Saturn."
匹配元組
使用元組可在一條switch語句中匹配復(fù)合值,并使用下劃線匹配元組中某個(gè)元素的所有可能值焕襟。
當(dāng)已經(jīng)匹配某個(gè)條件時(shí)陨收,之后的所有條件都將被忽略饭豹。
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")
}
// Prints "(1, 1) is inside the box"

值綁定
值綁定表示將匹配到的值命名為臨時(shí)常量或變量鸵赖。
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))")
}
// Prints "on the x-axis with an x value of 2"

當(dāng)某個(gè)條件正好匹配所有可能的剩余情況時(shí),則default語句可忽略拄衰。
Where
使用where語句對(duì)某個(gè)case添加額外條件:
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")
}
// Prints "(1, -1) is on the line x == -y"

復(fù)合case
使用逗號(hào)在一個(gè)case匹配多個(gè)條件它褪,條件過長時(shí)可多行顯示:
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")
}
// Prints "e is a vowel"
復(fù)合匹配中也可包含值綁定:
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")
}
// Prints "On an axis, 9 from the origin"
<br />
控制轉(zhuǎn)移語句
Swift有五種控制轉(zhuǎn)移語句:
- continue
- break
- fallthrough
- return
- throw
Continue
continue語句表示在循環(huán)中跳過本次循環(huán),直接開始下一次循環(huán)翘悉,而不結(jié)束循環(huán):
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let charactersToRemove: [Character] = ["a", "e", "i", "o", "u", " "]
for character in puzzleInput {
if charactersToRemove.contains(character) {
continue
} else {
puzzleOutput.append(character)
}
}
print(puzzleOutput)
// Prints "grtmndsthnklk"
Break
break語句立即結(jié)束執(zhí)行整個(gè)控制流語句茫打。
用于循環(huán)語句的break
當(dāng)在循環(huán)語句中使用break時(shí),break會(huì)立即結(jié)束執(zhí)行整個(gè)循環(huán)語句妖混。
用于switch語句的break
當(dāng)在switch語句中使用break時(shí)老赤,break會(huì)立即結(jié)束執(zhí)行整個(gè)switch。
Swift的switch語句中不用顯示使用break跳出匹配制市,但可以在某個(gè)case中可以插入break結(jié)束匹配以使意圖明確抬旺。
let numberSymbol: Character = "三" // Chinese symbol for the number 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).")
}
// Prints "The integer value of 三 is 3."
Fallthrough
Swift中,switch語句在匹配到某個(gè)case條件后會(huì)忽略之后所有case祥楣,不會(huì)自動(dòng)下一個(gè)case开财。若需要像C語言那樣跳入下個(gè)case中汉柒,可使用fallthrough關(guān)鍵字。
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)
// Prints "The number 5 is a prime number, and also an integer."
注意
fallthrough關(guān)鍵字不會(huì)檢查下個(gè)進(jìn)入的case判斷條件责鳍,只是簡單地跳入下一個(gè)case并執(zhí)行內(nèi)部代碼碾褂,與C語言中的switch語句相似。
標(biāo)簽語句
當(dāng)使用循環(huán)或條件嵌套語句時(shí)历葛,需要明確說明要使用break或continue語句來結(jié)束哪層控制語句正塌,這時(shí)使用標(biāo)簽語句對(duì)需要提前結(jié)束的控制語句做標(biāo)簽,然后在break或continue語句后接上已聲明的標(biāo)簽名來結(jié)束帶相同標(biāo)簽的語句恤溶。語法如下:
label name: while condition {
statements
}
<br />
guard語句
guard語句是if語句的變體传货,通過將判斷條件的主體執(zhí)行代碼放在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(person: ["name": "John"])
// Prints "Hello John!"
// Prints "I hope the weather is nice near you."
greet(person: ["name": "Jane", "location": "Cupertino"])
// Prints "Hello Jane!"
// Prints "I hope the weather is nice in Cupertino."
<br />
檢查API可用性
Swift支持檢查API可用性宏娄,避免代碼中使用不可用API導(dǎo)致意外錯(cuò)誤问裕。
當(dāng)嘗試使用不可用API時(shí),Swift會(huì)報(bào)告編譯錯(cuò)誤孵坚。
if #available(iOS 10, macOS 10.12, *) {
// Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
} else {
// Fall back to earlier iOS and macOS APIs
}
語法如下:
if #available(platform name version, ..., *) {
statements to execute if the APIs are available
} else {
fallback statements to execute if the APIs are unavailable
}