深入講解Swift中的模式匹配
模式匹配
模式匹配是 Swift 中非常常見的一種編程模式,使用模式匹配,可以幫助我們寫出簡明、清晰以及易讀的代碼,使我們的代碼變得簡潔而強(qiáng)大。
條件判斷中的模式匹配
條件判斷是我們使用最普遍的流程控制,在 Swift 中,只能接受 Bool 類型的值作為條件體;除了直接判斷 Bool 值之外,我們還能使用使用條件語句進(jìn)行可選綁定,這在我們開發(fā)中是非常常用的方式。
匹配枚舉值
在 Swift 中,創(chuàng)建的枚舉類型默認(rèn)是不可比較的(沒有實(shí)現(xiàn)Comparable協(xié)議),這就意味著我們不能直接使用==操作符來判斷兩個(gè)枚舉值是否相等,這種情況下,需要使用模式匹配:
創(chuàng)建一個(gè)枚舉類型:
enum Result {
case success
case failure
}
初始化一個(gè)枚舉值:
let result = Result.success
使用模式匹配來判斷創(chuàng)建的枚舉值的值:
if case .success = result {
print("Value of result is success.")
}
可選綁定
創(chuàng)建一個(gè)可選值:
let optionalInt: Int? = 1
使用可選綁定的方式進(jìn)行解包:
if let val = optionalInt {
print("The value of optionalInt is (val)")
}
func handleGuard() {
guard let val = optionalInt else {
return
}
print("The value of optionalInt is (val)")
}
handleGuard()
可選綁定的另外一種模式,這也是可選綁定中最基礎(chǔ)的模式:
if case .some(let val) = optionalInt {
print("The value of optionalInt is (val)")
}
還可以簡化為:
if case let val? = optionalInt {
print("The value of optionalInt is (val)")
}
循環(huán)中的模式匹配
問題來了,if let 模式的可選綁定,只能實(shí)現(xiàn)一個(gè)可選值的綁定,如果我們需要匹配一個(gè)數(shù)組里邊的可選值怎么辦呢?這時(shí)候我們就不能使用 if let 的形式了,需要使用到 if case let 的形式
創(chuàng)建一個(gè)包含可選值的數(shù)組:
let values: [Int?] = [1, nil, 3, nil, 5, nil, 7, nil, 9, nil]
進(jìn)行遍歷:
for val in values {
print("Value in values is (String(describing: val))")
}
或者:
var valuesIterator = values.makeIterator()
while let val = valuesIterator.next() {
print("Value in values is (String(describing: val))")
}
我們得到了所有的值與可選值,如果我們需要過濾可選值,我們可以這樣做:
for val in values.compactMap({ $0 }) {
print("Value in values is (val)")
}
這樣做,增加了時(shí)間復(fù)雜度,需要進(jìn)行兩次遍歷才能將數(shù)據(jù)過濾出來。我們可以使用模式匹配的方式來這樣做:
for case let val? in values {
print("Value in values is (val)")
}
或者:
valuesIterator = values.makeIterator()
while let val = valuesIterator.next(), val != nil {
print("Value in values is (String(describing: val))")
}
這樣就可以將 nil 值給過濾了,是不是很簡單?還可以使用 for case 匹配枚舉值數(shù)組:
let results: [Result] = [.success, .failure]
for case .success in results {
print("Values in results contains success.")
break
}
對(duì)于復(fù)雜的枚舉類型:
enum NetResource {
case http(resource: String)
case ftp(resource: String)
}
let nets: [NetResource] = [.http(resource: "https://www.baidu.com"), .http(resource: "https://www.apple.cn"), .ftp(resource: ftp://192.0.0.1)]
過濾 http 的值:
for case .http(let resource) in nets {
print("HTTP resource (resource)")
}
for 循環(huán)使用 where 從句
除此之外,我們還可以在 for 循環(huán)后邊跟上一個(gè) where 從句來進(jìn)行模式匹配:
for notNilValue in values where notNilValue != nil {
print("Not nil value: (String(describing: notNilValue!))")
}
查詢一個(gè)數(shù)組里邊所有能被3整除的數(shù):
let rangeValues = Array(0...999)
for threeDivideValue in rangeValues where threeDivideValue % 3 == 0 {
print("Three devide value: (threeDivideValue)")
}
查詢所有含有3的數(shù):
for containsThree in rangeValues where String(containsThree).contains("3") {
print("Value contains three: (containsThree)")
}
Switch 中的模式匹配
Switch 中的模式匹配也很常用,在 Switch 中合理地使用模式匹配可以為我們帶來很多好處,可以使我們的代碼更簡潔,同時(shí)可以減少代碼量和增加開發(fā)效率。
區(qū)間匹配
let value = 188
switch value {
case 0..<50:
print("The value is in range [0, 50)")
case 50..<100:
print("The value is in range [50, 100)")
case 100..<150:
print("The value is in range [100, 150)")
case 150..<200:
print("The value is in range [150, 200)")
case 200...:
print("The value is in range [200, ")
default: break
}
// The value is in range [150, 200)
匹配元組類型
創(chuàng)建一個(gè)元組類型:
let tuples: (Int, String) = (httpCode: 404, status: "Not Found.")
進(jìn)行匹配:
switch tuples {
case (400..., let status):
print("The http code is 40x, http status is (status)")
default: break
}
創(chuàng)建一個(gè)點(diǎn):
let somePoint = (1, 1)
進(jìn)行匹配:
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")
}
如上,我們?cè)谄ヅ涞臅r(shí)候可以使用下劃線 _ 對(duì)值進(jìn)行忽略:
switch tuples {
case (404, _):
print("The http code is 404 not found.")
default: break
}
在 switch 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")
}
總結(jié)
Swift 中模式匹配的種類
模式匹配可以說是 Swift 中非常強(qiáng)大的一種編程模式,使用良好的模式匹配,可以幫助我們寫出簡介、優(yōu)雅的代碼,Swift 中的模式匹配包括以下種類:
- 條件判斷:if, guard
- 可選綁定:if let, guard let, while let ...
- 循環(huán)體:for, while, repeat while
- switch
- do catch
什么時(shí)候使用 where 從句?
我們可以在前文的例子中看到,在很多進(jìn)行模式匹配的地方還使用了 where 從句,where 從句的作用就相當(dāng)于在模式匹配的基礎(chǔ)上在加上條件限制,使用 where 從句等價(jià)于:
for notNilValue in values {
if notNilValue != nil {
print("Not nil value: (String(describing: notNilValue!))")
}
}
可以看出,使用 where 從句可以使我們的代碼更加簡潔和易讀,什么時(shí)候使用 where ? 或者說在哪里可以使用 where ? Swift 文檔中并沒有對(duì) where 的詳細(xì)使用進(jìn)行介紹,但是在實(shí)踐中發(fā)現(xiàn),where 可以使用在以下地方:
- for 循環(huán)語句
- switch 分支
而對(duì)于 if, guard 與 while ,我們不能在其后面添加 where 從句,因?yàn)樗麄儽旧砜梢赃M(jìn)行多個(gè)條件的組合. where 從句還有一個(gè)用法就是對(duì)泛型類型進(jìn)行類型約束,這在泛型的章節(jié)中會(huì)有介紹.
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Swift教程之基礎(chǔ)數(shù)據(jù)類型詳解
這篇文章主要介紹了Swift教程之基礎(chǔ)數(shù)據(jù)類型詳解,本文詳細(xì)講解了Swift中的基本數(shù)據(jù)類型和基本語法,例如常量和變量、注釋、分號(hào)、整數(shù)、數(shù)值類型轉(zhuǎn)換等內(nèi)容,需要的朋友可以參考下2015-01-01
關(guān)于Swift 4.1中的Codable改進(jìn)詳解
這篇文章主要給大家介紹了關(guān)于Swift 4.1中的Codable改進(jìn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-02-02
Swift利用Decodable解析JSON的一個(gè)小問題詳解
這篇文章主要給大家介紹了關(guān)于Swift利用Decodable解析JSON的一個(gè)小問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-04-04
用SwiftUI實(shí)現(xiàn)3D Scroll滾動(dòng)效果的實(shí)現(xiàn)代碼
這篇文章主要介紹了用SwiftUI實(shí)現(xiàn)3D Scroll效果的實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)2020-04-04
Swift踩坑實(shí)戰(zhàn)之一個(gè)字符引發(fā)的Crash
swift通常都是通過對(duì)應(yīng)的signal來捕獲crash,下面這篇文章主要給大家介紹了關(guān)于Swift踩坑實(shí)戰(zhàn)之一個(gè)字符引發(fā)的Crash的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-02-02
Swift 3.0基礎(chǔ)學(xué)習(xí)之下標(biāo)
這篇文章主要介紹了Swift 3.0基礎(chǔ)學(xué)習(xí)之下標(biāo)的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用swift具有一定的參考價(jià)值,需要的朋友下面來一起看看吧。2017-03-03
swift中正確安全聲明一個(gè)單例的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于swift中如何正確安全聲明一個(gè)單例的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Swift 4中一些實(shí)用的數(shù)組技巧小結(jié)
這篇文章主要給大家分享了關(guān)于Swift 4中一些實(shí)用的數(shù)組技巧,文中通過示例代碼介紹的介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用swift具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03

