在Swift中很多地方都是用到了一个关键字where
,这个关键字的含义和数据库中的where
差不多,用于条件筛选(条件过滤),where
关键字在 Swift 中非常强大,那么在Swift中哪些地方用到了这个关键字呢?下面来总结一下。
一、 switch case中
let names = ["王小二","张三","李四","王五"]
for name in names {
switch name {
case let x where x.hasPrefix("王"):
print("姓王的有:\(x)")
default:
print("你好,\(name)")
}
}
二、for循环中
let array = [0,1,2,3,4,5,6,7,8,9]
for value in array where value % 2 == 0 {
print(value)
}
三、protocol协议中
protocol SomeProtocol{
}
extension SomeProtocol where Self:UIView{
//只给遵守myProtocol协议的UIView添加了拓展
func getInfo() -> String{
return "属于UIView类型"
}
}
extension UIButton:SomeProtocol{}
UIButton().getInfo()
四、Generic 泛型中
protocol AnOthorProtocol {
func say()
}
struct Bird: AnOthorProtocol {
func say() {
print("Hello World")
}
}
func genericFunc<T>(num: T) where T: AnOthorProtocol {
print(num)
}
genericFunc(num: Bird())
五、do catch异常处理中
enum ExceptionError:Error{
case httpCode(Int)
}
func throwError() throws {
throw ExceptionError.httpCode(404)
}
do{
try throwError()
}catch ExceptionError.httpCode(let httpCode) where httpCode == 404{
print("not found error")
}
网友评论