Swift where关键字的使用
来源:互联网 发布:手机格机软件 编辑:程序博客网 时间:2024/06/01 09:44
在一些Swift开源库里经常能看到 where 关键字的使用,但是查找开发文档的时候又找不到这个关键字。为了方便使用,这边总结了一些where关键字的用法。
1、用在do catch里面
enum ExceptionError:Error{ case httpCode(Int)}func throwError() throws { throw ExceptionError.httpCode(500)}//do catchdo{ try throwError()}catch ExceptionError.httpCode(let httpCode) where httpCode >= 500{ print("server error")}
2、用在switch里面
//switchvar value:(Int,String) = (1,"小明")switch value {case let (x,y) where x < 60: print("不及格")default: print("及格")}
3、for in
// for inlet 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、与协议结合
//protocolprotocol 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
// swift2.0中的写法``let sString = ""if let str = sString where str == ""{}let string:String? = "小刚"guard let str = string where str != "小明" else { fatalError("g看错人了") //}print("确实是小明")
合理的利用where关键字会令代码有更高的可读性、更高的简便性、更时尚。
阅读全文
0 0
- Swift where关键字的使用
- Swift语法-where关键字详解
- swift guard关键字使用
- Swift语法—— where语句使用
- Swift中的if语句使用where
- swift 语言中 let where 的意思
- Swift - final关键字的介绍,以及使用场景
- numpy where 的使用
- mongo $where的使用
- where子句的使用
- maybits where的使用
- Medoo Where的使用
- swift mutating关键字的用法
- WHERE 关键字无法与合计函数一起使用
- 3.Swift 中的where
- swift switch tuple where
- case where then 的使用
- Medoo Where的使用:条件
- Default Activity not found---Android studio
- WebView内存泄漏,如何让WebView清除更彻底
- 动手编写mapreduce---官方wordwount程序
- Java 反编译命令javap
- 《阿里巴巴Java开发手册(正式版)》--MySQL规约
- Swift where关键字的使用
- python基础知识(一)
- Cannot set the value of read-only property 'outputFile' for ApkVariantOutputImpl_Decorated
- oracle url的几种写法
- Cortex-M3异常
- STM32系统学习——SysTick(系统定时器)
- js在input失去焦点时对身份证、手机号、邮箱的合法性验证
- PostGresql 常用sql函数备忘录
- Linux 加密压缩的方法