在一些Swift開源庫里經(jīng)常能看到 where 關鍵字的使用包警,但是查找開發(fā)文檔的時候又找不到這個關鍵字图甜。為了方便使用,這邊總結了一些where關鍵字的用法囚灼。
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阅签、與范型結合
func genericFunction<S>(str:S) where S:ExpressibleByStringLiteral{
print(str)
}
//第二種寫法
func genericFunction<S:ExpressibleByStringLiteral>(str:S){
print(str)
}
5、與協(xié)議結合
//protocol
protocol aProtocol{}
extension aProtocol where Self:UIView{
//只給遵守myProtocol協(xié)議的UIView添加了拓展
//強大的協(xié)議拓展 可以給協(xié)議添加默認實現(xiàn) 面向協(xié)議編程的基礎
func getString() -> String{
return "string"
}
}
class MyView:UIView{}
extension MyView:aProtocol{}
let myView = MyView()
let aStr = myView.getString()
注意:以下是Swift3.0取消的 where 寫法
本來在while循環(huán)中也能使用的where蝎抽,現(xiàn)在變成了這個樣子\
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
// swift2.0中的寫法``
let sString = ""
if let str = sString where str == ""{
}
let string:String? = "小剛"
guard let str = string where str != "小明" else {
fatalError("g看錯人了") //
}
print("確實是小明")
合理的利用where關鍵字會令代碼有更高的可讀性樟结、更高的簡便性锥涕、更時尚。