Where
switch
/// switch 條件語句的判斷
///
func whereSwitch(value: (Int, String)) {
switch value {
case let (x,y) where x < 60:
print("\(y)不及格")
case let (x,y) where x > 90:
print("\(y)優秀")
case let (_,y):
print("\(y)及格")
}
}
for loop
/// 循環遍歷的時候條件判斷
///
func whereLoop() {
let indexs = [1, 2, 3, 4]
let values = [1: "1", 2: "2"]
for index in indexs where values[index] != nil {
print("loop value \(index) - \(String(describing: values[index]))")
}
}
do catch
/// do catch 部分
///
///
class DemoError : Error {
var code: Int?
init() {
}
}
func whereDoCatch() {
do {
let error = DemoError()
error.code = 500
throw error
} catch let e as DemoError where e.code == 500 {
print("error code 500")
} catch {
print("Other error: \(error)")
}
}
protocol 與 where結合部分
/// where 與協議結合部分
protocol AnimalProtocol {}
class Animal {
}
extension AnimalProtocol where Self:Animal {
func name() -> String {
return "animal"
}
}
class Cat: Animal {
}
class Dog {
}
extension Cat: AnimalProtocol {
}
extension Dog: AnimalProtocol {
}
func printName() -> Void {
let cat = Cat()
print(cat.name())
let dog = Dog()
dog.name()
/// 使用報錯 -- Referencing instance method 'name()' on 'AnimalProtocol' requires that 'Dog' inherit from 'Animal'
}
與范型結合
/// 與范型結合使用
///
///
class WhereT {
func printLog() {
}
}
func genericFunction<S>(str:S) where S:WhereT {
str.printLog()
}
class WhereImp: WhereT {
}
func WhereTDemo() -> Void {
genericFunction(str: WhereImp())
/// 報錯 -- Global function 'genericFunction(str:)' requires that 'String' inherit from 'WhereT'
genericFunction(str: "")
}