Swift

Swift where关键字详解

在Swift语法里where关键字的作用跟SQL的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. 与范型结合
//第一种写法
// 在使用泛型的时候也常常用到where对泛型加以限制
func genericFunction<S>(str:S) where S:ExpressibleByStringLiteral{
    print(str)
}
//第二种写法
func genericFunction<S:ExpressibleByStringLiteral>(str:S){
    print(str)
}
5. 与协议结合
protocol SomeProtocol {
    func someMethod()
}
 
class A: SomeProtocol {
    let a = 1
    
    func someMethod() {
       print("call someMethod")
    }
}
 
class B {
    let a = 2
}
 
//基类A继承了SomeProtocol协议才能添加扩展
extension SomeProtocol where Self: A {
    func showParamA() {
        print(self.a)
    }
}
//反例,不符合where条件
extension SomeProtocol where Self: B {
    func showParamA() {
        print(self.a)
    }
}
let objA = A()
let objB = B()  //类B没实现SomeProtocol, 所有没有协议方法
objA.showParamA()  //输出1