Swift where 关键字

在一些Swift开源库里经常能看到 where 关键字的使用,但是查找apple帮助文档的时候又找不到这个关键字,真是太奇怪了。为了方便使用,这边总结了一些where关键字的用法,希望能推动大家写出更加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、与范型结合

//第一种写法
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()

注意:以下是Swift3.0取消的 where 写法

本来在while循环中也能使用的where,现在变成了这个样子
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 现在我也不知道怎么使用Swift化的写法来写这个表达式,希望能知道的朋友告诉一下,谢谢

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

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一直没有时间好好看一下swift,最近复习了一遍语法,这里记录swift学习过程中遇到的一些问题和要点,和Obje...
    bomo阅读 7,067评论 0 25
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,194评论 4 61
  • 楼台映月水茫茫。暗流伤,又何妨。南雁几重,总与话斜阳。 梦里寻君千百度,缠缱倦,夜来香。无语凝咽,唯有泪千行。 秋...
    一滴露水阅读 3,474评论 4 12
  • 1 冬天的寒风吹着口哨,口哨声跳上屋顶,越过房檐,最后滑进烟道。我坐在一张木板床上看报,报缝里面小字体吸引了我的注...
    锄风少年阅读 2,372评论 2 2
  • 你是不是有这样的苦恼? 家里无论怎么收拾都收拾不完,今天整理干净了,明天又乱了,一旦哪天不想收拾,第二天就会加倍凌...
    迷夏的小岛阅读 2,854评论 1 7