swift小知识点之where 关键字(额外条件语句)

  where 语句可以用来设置约束条件、限制类型,让代码更加简洁、易读。在一些Swift开源库里经常能看到 where 关键字的使用,为了方便使用,以下总结了一些where关键字的用法,

1、用在do catch里面

enum ExceptionError:Error {
    case httpCode(Int)
}

func thorowError() throws {
    throw ExceptionError.httpCode(500)
}

///do catch
do{
    
} catch ExceptionError.httpCode(let httpCode) where httpCode >= 500 {
    print("server Error")
}

2、用在switch里面

var value:(Int, String) = (1, "小明")
switch value {
case let (x,_) where x < 60:
    print("不及格")
default:
    print("及格")
}

3、for in

let arrayOne = [1,2,3,4,5]
let dictionary = [1:"hehe1",2:"hehe2"]
for i in arrayOne where dictionary[i] != nil {

}

4、与范型结合

//第一种写法
func genericFunction<S>(str:S) where S:ExpressibleByStringLiteral{
    print(str)
}
//第二种写法
func genericFunction<S:ExpressibleByStringLiteral>(str:S){
    print(str)
}

5、与协议结合

where的作用是限定协议扩展有效条件, 在where语句中,你可以使用Self关键字来代表协议的遵守者,可以指定遵守者是某个类的子类或者遵守了某个协议

//protocol
protocol aProtocol{}
extension aProtocol where Self:UIView{
    //只给遵守myProtocol协议的UIView添加了拓展
    //强大的协议拓展  可以给协议添加默认实现   面向协议编程的基础
    func getString() -> String{
        return "string"
    }
}
class MyView:UIView{}
extension MyView:aProtocol{}
let myView = MyView()
let aStr = myView.getString()

6、Swift3.0取消的 where 写法

本来在while循环中也能使用的where,现在变成了这个样子

1、while 现在拿掉了where关键字(用","替代了where)
//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 现在拿掉了where关键字(用","替代了where)
  • swift2.0中的写法``
let sString = ""
if let str = sString where str == ""{
}

let string:String? = "小刚"
guard let str = string where str != "小明" else {
    fatalError("g看错人了") //
}
print("确实是小明")
  • swift5.0中的写法``
let sString:String? = ""
if let str = sString, str == ""{
}

let string:String? = "小刚"
guard let str = string, str != "小明" else {
    fatalError("g看错人了") //
}
print("确实是小明")

合理的利用where关键字会令代码有更高的可读性、更高的简便性、更时尚

posted on 2021-07-08 13:20  梁飞宇  阅读(601)  评论(0)    收藏  举报