【IOS】Swift中 where关键字的使用

Swift开源库里经常能看到 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、与协议结合

//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 写法
1.本来在while循环中也能使用的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

// swift2.0中的写法
let sString = ""
if let str = sString where str == ""{
}

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

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值