The WHERE keyword is often used in the Swift open source library

1. Do catch

enum ExceptionError:Error{
    case httpCode(Int)
}
func throwError() throws {
    throw ExceptionError.httpCode(500)
}
//do catch
do{
    try throwError()
}catch ExceptionError.httpCode(let httpCode) where httpCode >= 500{
    print("server error")
}

Copy the code

2. Use it in switch

//switch var value:(Int,String) = (1,"小 小 ") switch value {case let (x,y) where x < 60: print(" 小 小 ") default: Print (" pass ")}Copy the code

3, for in

// for let arrayOne = [1,2,3,4,5] let dictionary = [1:"hehe1",2:"hehe2"] for I in arrayOne where dictionary[I]! = nil { print(i) }Copy the code

4. Combine with the paradigm

/ / the first writing func genericFunction < S > (STR: S) where S: ExpressibleByStringLiteral {print (STR)} / / the second writing func genericFunction<S:ExpressibleByStringLiteral>(str:S){ print(str) }Copy the code

5. Combine with the agreement

//protocol protocol aProtocol{} extension aProtocol where Self:UIView{// Extension aProtocol where Self:UIView{// Func getString() -> String{return "String"}} Class MyView:UIView{} extension MyView:aProtocol{}  let myView = MyView() let aStr = myView.getString()Copy the code

6. The version is cancelled

Note: Swift3.0 cancelates where

  1. Where, which could have been used in the while loop,
Var arrayTwo:[Int]? = [] while let arr = arrayTwo where arr.count < 5 { arrayTwo? Var arrayTwo:[Int]? = [] while let arr = arrayTwo , arr.count < 5 { arrayTwo? .append(1) }Copy the code

2. If and guard

If + WHERE and guard + WHERE are no longer supported, replaced by commas

Let sString = "" if let STR = sString where STR == ""{} let string: string? If (STR = string where STR = string) else {fatalError("g ") // print(" g ")Copy the code
// Let string: string? Else {fatalError("g is wrong ") // print(" g is wrong ")Copy the code

Proper use of the WHERE keyword makes your code more readable and simpler.