swift where與匹配模式的實例詳解
前言:
在眾多 Swift 提供給 Objective-C 程序員使用的新特性中,有個特性把自己偽裝成一個無聊的老頭,但是卻在如何優雅的解決“鞭尸金字塔“的問題上有著巨大的潛力。很顯然我所說的這個特性就是 switch 語句, 對于很多 Objective-C 程序員來說,除了用在 Duff's Device 上比較有趣之外,switch 語句非常笨拙,與多個 if 語句相比,它幾乎沒有任何優勢。
1、基本使用
Swift中switch語句case后面可以用where對條件進行限制
let point = (3,3)
switch point{
case let (x,y) where x == y:
print("It's on the line x == y!")
case let (x,y) where x == -y:
print("It's on the line x == -y!")
case let (x,y):
print("It's just an ordinary point.")
print("The point is ( \(x) , \(y) )")
}
2、使用if - case - where語句替代switch語句的使用方法
let age = 19
switch age{
case 10...19:
print("You're a teenager.")
default:
print("You're not a teenager.")
}
if case 10...19 = age{
print("You're a teenager.")
}
if case 10...19 = age where age >= 18{
print("You're a teenager and in a college!")
}
注意:case條件必須放在”=”之前
swift 3.0以后if case 后面的”where”用”,”代替
3、if-case 與元組組合使用(元組解包使用)
let vector = (4,0)
if case ( let x , 0 ) = vector where x > 2 && x < 5{
print("It's the vector!")
}
4、case - where 與循環組合使用
for i in 1...100{
if i%3 == 0{
print(i)
}
}
for case let i in 1...100 where i % 3 == 0{
print(i)
}
使用case限制條件可以大大減少代碼量,使用起來非常方便,是swift語言的一大特色,好好掌握可以寫出很優美的簡潔的代碼
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!