控制流
For-In循環(huán)
使用for-in
循環(huán)迭代數(shù)組
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)!")
}
使用for-in
循環(huán)迭代字典
let airports = ["job": "將軍", "age": "16", "name": "zhangfei"]
for (key,value) in airports {
print("\(key)")
print("\(value)")
}
使用for-in
循環(huán)迭代數(shù)值范圍
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
使用for-in
循環(huán)迭代數(shù)值范圍之使用stride(from:to:by :)
函數(shù):返回從起始值到結束值(不包括),跳過指定量的序列。從開始值起序列中的每個連續(xù)值都會增加相同范圍的幅度,直到下一個值等于或超過結束值绝淡。(以指定間隔迭代特定數(shù)值時的序列)。符合Strideable
協(xié)議的任何類型的值都可以使用此函數(shù),例如整數(shù)或浮點類型搪锣。
for item in stride(from: 0, to: 60, by: 5) {
print(item, separator: "", terminator: " ")//!< 0 5 10 15 20 25 30 35 40 45 50 55
}
for item in stride(from: 0, to: Double.pi * 2, by: .pi/2) {
print(item, separator: "", terminator: " ")//!<0.0 1.5707963267948966 3.141592653589793 4.71238898038469
}
使用for-in
循環(huán)迭代數(shù)值范圍之使用stride(from:through:by:)
函數(shù):返回從起始值到結束值(可能包括),跳過指定量的序列彩掐。(以指定間隔迭代特定數(shù)值時的序列)與stride(from:to:by :)
函數(shù)區(qū)別于它可能會包括結束值构舟。
for item in stride(from: 0, through: 60, by: 5) {
print(item, separator: "", terminator: " ")//!< 0 5 10 15 20 25 30 35 40 45 50 55 60
}
for item in stride(from: 0, through: Double.pi * 2, by: .pi/2) {
print(item, separator: "", terminator: " ")//!<0.0 1.5707963267948966 3.141592653589793 4.71238898038469 6.283185307179586
}
While循環(huán)
Swift提供了兩種while
循環(huán):
- while:在每次循環(huán)開始時判斷條件。
- repeat-while:在每次循環(huán)結束時判斷條件堵幽。
While
while
循環(huán)開始時判斷條件是否成立狗超,若true
立即執(zhí)行方法體,直到條件變?yōu)?code>false時停止執(zhí)行朴下。
let adc = 10
var apc = 0;
while apc < adc {
apc += 1 //!< 必須要有終止的條件 若 apc < adc 恒成立則程序陷入死循環(huán)
print("條件成立") //10
}
Repeat-While
repeat-while
循環(huán):while
循環(huán)的變體努咐,類似于其他語言中的do-while
,先執(zhí)行單個循環(huán)殴胧,再考慮循環(huán)條件渗稍,若為true
繼續(xù)重復循環(huán)佩迟,直到條件為false
停止執(zhí)行。
let adc = 10
var apc = 0;
repeat {
apc += 1
print("條件成立") //!< 10次
}while apc < adc
條件語句
If
let adc = 20
if adc <= 32 {
print("adc <= 32")
} else if adc >= 86 {
print("adc >= 86")
} else {
print("32 <adc< 86")
}
Switch
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
語句執(zhí)行時不會貫穿每個case竿屹。而C和Objective-C中的switch
語句需要顯式的break
語句报强,若不添加則會向下貫穿到所匹配項下面的每個case
,并執(zhí)行拱燃。
MyEnumType type = MyEnumType2;
switch (type) {
case MyEnumType1:
NSLog(@"MyEnumType1");
case MyEnumType2:
NSLog(@"MyEnumType2");
case MyEnumType3:
NSLog(@"MyEnumType3");
}
/*
MyEnumType2
MyEnumType3
*/
Swift中的switch
語句只要第一個匹配的switch
的case
完成秉溉,整個switch語句就會完成執(zhí)行,而不需要顯式的break
語句扼雏。
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
print("The letter A")
default:
print("Not the letter A")
}
Range匹配
switch
語句可以檢測其判斷的值坚嗜,是否包含在某個case的范圍內。
let adc = 20
var apc = 0;
var result = ""
switch adc {
case 0...10:
result = "0...10"
case 11..<20:
result = "11..<20"
case 20...30:
result = "20...30"
default:
result = "beyond of range"
}
print(result)//!< 20...30
元組
switch
語句可以判斷元組的值诗充,是否符合某個case苍蔬。可以針對元組不同的值或值的間隔范圍來測試元組的每個元素蝴蜓〉螅或者,使用下劃線字符(通配符)_
來匹配任何可能的值茎匠。
let tuples : (Int,String,Int) = (404,"not found",-1)
switch tuples {
case (300,"精準匹配1",0):
print("精準匹配1")
case (0...200,"范圍匹配1",-2...10):
print("范圍匹配1")
case (_,_,-2...2):
print("通配符匹配元組前兩個,范圍匹配最后一項")
default:
print("沒有匹配到")
}
值綁定
switch
中case
可以命名它所匹配到的臨時的常量或變量格仲, 以便在case
對應的方法中使用。這種行為稱為值綁定诵冒。
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("橫坐標\(x)")
case (0, let y):
print("縱坐標 \(y)")
case let (x, y):
print("任何點 (\(x), \(y))")
}
上述switch語句中case(let x凯肋,0)
匹配y
值為0的任何點,并將點的x
值賦給臨時常量x
汽馋。case(0侮东,let y)
匹配x
值為0的任何點,并將點的y
值賦給臨時常量y
豹芯。let(x悄雅,y)
,聲明了一個可以匹配任何值的含有兩個占位符常量的元組铁蹈。因為匹配所有可能的剩余值宽闲,所以不需要default case
來使switch語句窮舉。
Where
switch語句中case可以使用where
子句來檢查其他條件握牧。
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x==y:
print("匹配到x與y相同的情況")
case let(x,y) where x == -y:
print("匹配到x與y為相反數(shù)的情況")//!<匹配到x與y為相反數(shù)的情況
default:
print("沒有匹配的結果")
}
上述示例中switch語句中的case聲明占位符常量x
和y
容诬,它們暫時從yetAnotherPoint
獲取元組值。這些常量用作where
子句的一部分沿腰,用于創(chuàng)建動態(tài)過濾器览徒。僅當where
子句的條件對占位符常量x
和y
的計算結果為true
時,switch語句的case才會成功匹配當前值矫俺。
復合使用
switch
語句中若有多個case共享的相同方法體吱殉,可以通過在case
之后組合多個模式,每個模式之間用逗號隔開來表示厘托。多個模式中任一個匹配友雳,則認為這個case
是匹配的。同時case
之后的多個模式也可以多行表示铅匹。
let someCharater = "e"
switch someCharater {
case "a","o","e","f":
print("事例1押赊,匹配成功")//!< log
case "b","v","r","h":
print("事例2,匹配成功")
default:
print("未匹配")
}
//復合事例中的值綁定包斑,綁定的值類型必須匹配流礁。case (let x, let y), (0, let x)這種是不被允許的 因為方法體中使用x,y時罗丰,若匹配的是 (0, let x)則y 無效神帅。因為相同的值綁定應該存在于所有`case`之后的模式中。
let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let x, 0), (0, let x)://!< 'x' must be bound in every pattern:'x'必須綁定在每個模式中
print("匹配成功")
default:
print("未匹配")
}
switch的case
后對應多個模式的復合事例中萌抵,每個模式對應的綁定的值類型必須匹配找御,并且相同的一組值綁定,如(let x, let y)
其中x
绍填,y
稱為一組值綁定霎桅,應該存在于所有case
之后的模式中。
控制轉移語句
控制轉移語句通過將控制從一段代碼轉移到另一段代碼來改變代碼執(zhí)行的順序讨永。Swift有五個控制轉移語句:
- continue
- break
- fallthrough
- return
- throw
continue
continue
語句:跳出正在執(zhí)行的循環(huán)語句滔驶,立即開始執(zhí)行下一次循環(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
}
puzzleOutput.append(character)
}
print(puzzleOutput) //!< break下跳出循環(huán),立即開始下一次迭代卿闹,輸出為:grtmndsthnklk
break
break
語句:立即結束所有控制流語句的執(zhí)行揭糕。
循環(huán)語句中的break
:循環(huán)語句中使用break,會立即結束循環(huán)的執(zhí)行比原,并在循環(huán)方法體}
之后將控制權轉移給后續(xù)的代碼插佛。
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let charactersToRemove: [Character] = ["a", "e", "i", "o", "u", " "]
for character in puzzleInput {
if charactersToRemove.contains(character) {
break
}
puzzleOutput.append(character)
}
print(puzzleOutput) //!< break下跳出循環(huán)不在開始,輸出為gr
switch語句中的break
:在switch語句中使用break
量窘,會使switch語句立即結束其執(zhí)行雇寇,并移交控制權。
let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let x, 0), (0, let x):
print("匹配成功")
default:
break
}
貫穿(Fallthrough)
如果需要C或Objective-C的貫穿行為蚌铜,則可以使用fallthrough
關鍵字锨侯。
let describe = 5
var description = ""
switch describe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += "I am"
fallthrough
case 18:
description += " bob" //!< case 去掉fallthrough 則輸出I am bob
fallthrough
default:
description += " and you?"
}
print(description)//!< I am bob and you?
標簽語句
在Swift中,其他循環(huán)和條件語句中可以嵌套循環(huán)和條件語句冬殃,從而創(chuàng)建復雜的控制流結構囚痴。但是,循環(huán)和條件語句都可以使用break
語句過早地結束執(zhí)行审葬。因此深滚,需要明確break
語句終止的循環(huán)或條件語句奕谭,或明確continue
語句應該影響哪個循環(huán)是非常必要的,故會用到標簽語句痴荐。
var result = ""
let adc = 30
forLabel : for item in 9...adc {
switchLabel :switch item {
case 0...10:
result += " 0...10"
break switchLabel //!<swift中break是默認的
case 11..<20: //!< 若是11..<20區(qū)間則跳出for循環(huán)血柳,開始下次迭代
continue forLabel
case 20://!< 若是20 則立即終止for循環(huán)
result += " 終止for循環(huán)"
break forLabel
default:
result += "beyond of range"
}
}
print(result) //!< 0...10 0...10 終止for循環(huán)
提前退出(throw,return)
與if
語句一樣,guard
語句根據(jù)表達式的布爾值執(zhí)行語句生兆。使用guard語句要求條件必須為true
才能執(zhí)行guard
語句之后的代碼难捌。與if
語句不同,guard
語句總是有一個else
子句 如果條件為false
鸦难,則執(zhí)行else
子句中的代碼根吁。guard
的else
子句不能向下貫穿,必須使用轉移控制的語句return
或throw
才能退出作用域合蔽。
//return
let adc = 30
//! guard方法體不能向下貫穿击敌,需要使用`return`或`throw`退出作用域
guard adc > 30 else {
print("條件不成立")
return //!< 提前結束了
}
//throw退出作用域
guard adc > 30 else {
print("條件不成立")
throw HttpError.authError
}
檢查API可用性
Swift支持檢查API可用性:編譯器使用SDK中的可用性信息來驗證使用的API是否在指定部署目標上可用。確保我們不會在給定部署目標上使用不可用的API拴事∮拚可以在if
或guard
語句中使用可用性條件進行判斷。
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
}
參考資料:
swift 5.1官方編程指南