Swift中where关键字的应用场景和用法
//: [Previous](@previous)
import Foundation
import UIKit
var str = "Hello, playground"
//: [Next](@next)
//笔记记录swift中where关键字的适用场景和方法
//1.用在do...catch...中
enum ExceptionError:Error{
case httpCode(Int)
}
do {
throw ExceptionError.httpCode(500)
}
catch ExceptionError.httpCode(let code) where code > 500 {
print("server error")
}
//2.switch语句中
var value:(Int,String) = (1,"小明")
switch value {
case let (x,y) where x < 60:
print("不及格")
default:
print("及格")
}
//3.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 genericity1<S>(s: S) where S: Equatable {
}
//另一种写法
func genericity2<S: Equatable>(s: S) {
}
//5.与协议结合
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()
//给数组中元素遵守Equatable协议的数组添加扩展
public extension Array where Array.Element : Equatable {
/// 移除数组中的一个指定元素
///
/// - Parameter obj: 指定的元素
public mutating func removeObject(_ obj: Array.Element) {
guard let idx = self.index(of: obj) else {
return
}
remove(at: idx)
}
}