模式匹配是 Swift 中很是常見的一種編程模式,使用模式匹配,能夠幫助咱們寫出簡明、清晰以及易讀的代碼,使咱們的代碼變得簡潔而強大。git
條件判斷是咱們使用最廣泛的流程控制,在 Swift 中,只能接受 Bool 類型的值做爲條件體;除了直接判斷 Bool 值以外,咱們還能使用使用條件語句進行可選綁定,這在咱們開發中是很是經常使用的方式。github
在 Swift 中,建立的枚舉類型默認是不可比較的(沒有實現Comparable
協議),這就意味着咱們不能直接使用==
操做符來判斷兩個枚舉值是否相等,這種狀況下,須要使用模式匹配:編程
建立一個枚舉類型:swift
enum Result {
case success
case failure
}
複製代碼
初始化一個枚舉值:數組
let result = Result.success
複製代碼
使用模式匹配來判斷建立的枚舉值的值:app
if case .success = result {
print("Value of result is success.")
}
複製代碼
建立一個可選值:ide
let optionalInt: Int? = 1
複製代碼
使用可選綁定的方式進行解包:ui
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()
複製代碼
可選綁定的另一種模式,這也是可選綁定中最基礎的模式:spa
if case .some(let val) = optionalInt {
print("The value of optionalInt is (val)")
}
複製代碼
還能夠簡化爲:code
if case let val? = optionalInt {
print("The value of optionalInt is (val)")
}
複製代碼
問題來了,if
let
模式的可選綁定,只能實現一個可選值的綁定,若是咱們須要匹配一個數組裏邊的可選值怎麼辦呢?這時候咱們就不能使用 if
let
的形式了,須要使用到 if
case
let
的形式
建立一個包含可選值的數組:
let values: [Int?] = [1, nil, 3, nil, 5, nil, 7, nil, 9, nil]
複製代碼
進行遍歷:
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)")
}
複製代碼
這樣作,增長了時間複雜度,須要進行兩次遍歷才能將數據過濾出來。咱們可使用模式匹配的方式來這樣作:
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
匹配枚舉值數組:
let results: [Result] = [.success, .failure]
for case .success in results {
print("Values in results contains success.")
break
}
複製代碼
對於複雜的枚舉類型:
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
循環使用 where
從句除此以外,咱們還能夠在 for
循環後邊跟上一個 where
從句來進行模式匹配:
for notNilValue in values where notNilValue != nil {
print("Not nil value: (String(describing: notNilValue!))")
}
複製代碼
查詢一個數組裏邊全部能被3整除的數:
let rangeValues = Array(0...999)
for threeDivideValue in rangeValues where threeDivideValue % 3 == 0 {
print("Three devide value: (threeDivideValue)")
}
複製代碼
查詢全部含有3的數:
for containsThree in rangeValues where String(containsThree).contains("3") {
print("Value contains three: (containsThree)")
}
複製代碼
Switch 中的模式匹配也很經常使用,在 Switch 中合理地使用模式匹配能夠爲咱們帶來不少好處,可使咱們的代碼更簡潔,同時能夠減小代碼量和增長開發效率。
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)
複製代碼
建立一個元組類型:
let tuples: (Int, String) = (httpCode: 404, status: "Not Found.")
複製代碼
進行匹配:
switch tuples {
case (400..., let status):
print("The http code is 40x, http status is (status)")
default: break
}
複製代碼
建立一個點:
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")
}
複製代碼
如上,咱們在匹配的時候可使用下劃線 _
對值進行忽略:
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")
}
複製代碼
模式匹配能夠說是 Swift 中很是強大的一種編程模式,使用良好的模式匹配,能夠幫助咱們寫出簡介、優雅的代碼,Swift 中的模式匹配包括如下種類:
if
, guard
if
let
, guard
let
, while
let
...for
, while
, repeat
while
switch
do
catch
where
從句?咱們能夠在前文的例子中看到,在不少進行模式匹配的地方還使用了 where
從句,where
從句的做用就至關於在模式匹配的基礎上在加上條件限制,使用 where
從句等價於:
for notNilValue in values {
if notNilValue != nil {
print("Not nil value: (String(describing: notNilValue!))")
}
}
複製代碼
能夠看出,使用 where
從句可使咱們的代碼更加簡潔和易讀,何時使用 where
? 或者說在哪裏可使用 where
? Swift 文檔中並無對 where
的詳細使用進行介紹,可是在實踐中發現,where
可使用在如下地方:
for
循環語句switch
分支而對於 if
, guard
與 while
,咱們不能在其後面添加 where
從句,由於他們自己能夠進行多個條件的組合. where
從句還有一個用法就是對泛型類型進行類型約束,這在泛型的章節中會有介紹.