1. For-In循環(huán)
for-in
循環(huán)中如果我們不需要知道每一次循環(huán)中計(jì)數(shù)器具體的值,用下劃線_
替代循環(huán)中的變量绑青,能夠忽略當(dāng)前值赏半。
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
2. While循環(huán)
while
循環(huán)在這里忽略講解,主要說說while
循環(huán)的另一種形式repeat-while
盒蟆,它和while
的區(qū)別是在判斷循環(huán)條件之前鬼店,先執(zhí)行一次循環(huán)代碼塊网棍,然后重復(fù)循環(huán)直到條件為false
,類似于其他語言中的do-while
薪韩。
3. 條件語句
Swift提供兩種類型的條件語句:If
語句和switch
語句确沸。
switch
語句不需要再case
分支中顯式地使用break
,不存在隱式貫穿俘陷,每個(gè)case
分支都必須包含至少一條語句罗捎。
單個(gè)case
語句可以復(fù)合匹配和區(qū)間匹配。
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. 復(fù)合匹配
當(dāng)多個(gè)條件可以使用同一種方法來處理時(shí),可以將這幾種可能放在同一個(gè)case
后面捉偏,并且用逗號隔開倒得。
8. 控制轉(zhuǎn)移語句
8.1 Continue
continue
語句告訴一個(gè)循環(huán)體立刻停止本次循環(huán),重新開始下次循環(huán)夭禽。
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
語句會立刻結(jié)束整個(gè)循環(huán)體的執(zhí)行霞掺。
8.3 貫穿
Swift中的switch
不會從上一個(gè)case
分支落入到下一個(gè)case
分支中。如果你需要C風(fēng)格的貫穿特性讹躯,可以在每個(gè)需要該特性的case
分支中使用fallthrough
關(guān)鍵字菩彬。
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 提前退出
條件為真時(shí)缠劝,執(zhí)行guard
語句后面的代碼,不同于if
語句骗灶,一個(gè)guard
語句總是有一個(gè)else
從句惨恭,如果條件不為真則執(zhí)行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
免都。