在一些Swift開(kāi)源庫(kù)里經(jīng)常能看到 where 關(guān)鍵字的使用,但是查找apple幫助文檔的時(shí)候又找不到這個(gè)關(guān)鍵字,真是太奇怪了。為了方便使用,這邊總結(jié)了一些where關(guān)鍵字的用法,希望能推動(dòng)大家寫出更加Swift的代碼。
1、用在do catch里面
enum ExceptionError:Error{
case httpCode(Int)
}
func throwError() throws {
throw ExceptionError.httpCode(500)
}
//do catch
do{
try throwError()
}catch ExceptionError.httpCode(let httpCode) where httpCode >= 500{
print("server error")
}
2、用在switch里面
//switch
var value:(Int,String) = (1,"小明")
switch value {
case let (x,y) where x < 60:
print("不及格")
default:
print("及格")
}
3、for in
// for in
let arrayOne = [1,2,3,4,5]
let dictionary = [1:"hehe1",2:"hehe2"]
for i in arrayOne where dictionary[i] != nil {
print(i)
}
4、與范型結(jié)合
//第一種寫法
func genericFunction<S>(str:S) where S:ExpressibleByStringLiteral{
print(str)
}
//第二種寫法
func genericFunction<S:ExpressibleByStringLiteral>(str:S){
print(str)
}
5、與協(xié)議結(jié)合
//protocol
protocol aProtocol{}
extension aProtocol where Self:UIView{
//只給遵守myProtocol協(xié)議的UIView添加了拓展
//強(qiáng)大的協(xié)議拓展 可以給協(xié)議添加默認(rèn)實(shí)現(xiàn) 面向協(xié)議編程的基礎(chǔ)
func getString() -> String{
return "string"
}
}
class MyView:UIView{}
extension MyView:aProtocol{}
let myView = MyView()
let aStr = myView.getString()
注意:以下是Swift3.0取消的 where 寫法
本來(lái)在while循環(huán)中也能使用的where,現(xiàn)在變成了這個(gè)樣子
1、while
//while swift2.0中的寫法
var arrayTwo:[Int]? = []
while let arr = arrayTwo where arr.count < 5 {
arrayTwo?.append(1)
}
//Swift3.0的寫法
var arrayTwo:[Int]? = []
while let arr = arrayTwo , arr.count < 5 {
arrayTwo?.append(1)
}
2、if 和 guard 現(xiàn)在我也不知道怎么使用Swift化的寫法來(lái)寫這個(gè)表達(dá)式,希望能知道的朋友告訴一下,謝謝
// swift2.0中的寫法``
let sString = ""
if let str = sString where str == ""{
}
let string:String? = "小剛"
guard let str = string where str != "小明" else {
fatalError("g看錯(cuò)人了") //
}
print("確實(shí)是小明")
合理的利用where關(guān)鍵字會(huì)令代碼有更高的可讀性、更高的簡(jiǎn)便性、更時(shí)尚??