在Swift中很多地方都是用到了一个关键字where
,这个关键字的含义和数据库中的where
差不多,用于条件筛选(条件过滤),那么在Swift中哪些地方用到了这个关键字呢?下面来总结一下。
var value = 60
switch value {
case let x where x < 60:
print("不及格")
default:
print("及格")
}
let array = [0,1,2,3,4,5,6,7,8,9]
for value in array where value % 2 == 0 {
print(value)
}
protocol SomeProtocol{
}
extension SomeProtocol where Self:UIView{
//只给遵守myProtocol协议的UIView添加了拓展
func getInfo() -> String{
return "属于UIView类型"
}
}
extension UIButton:SomeProtocol{}
UIButton().getInfo()
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())
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")
}