天天看點

Swift(學習):模式比對模式(Pattern)通配符模式(Wildcard Pattern)辨別符模式(Identifier Pattern)值綁定模式(Value-Binding Pattern)元組模式(Tuple Pattern)枚舉Case模式(Enumeration Case Pattern)可選模式(Optional Pattern)類型轉換模式(Type- Casting Pattern)表達式模式(Expression Pattern)自定義表達式模式Where

模式(Pattern)

  • 什麼是模式?
  • 模式是用于比對的規則,比如switch的case、捕捉錯誤的catch、if\guard\while\for語句的條件等
  • Swift中的模式有
  1. 通配符模式(Wildcard Pattern) 
  2. 辨別符模式(Identifier Pattern) 
  3. 值綁定模式(Value-Binding Pattern) 
  4. 元組模式(Tuple Pattern) 
  5. 枚舉Case模式(Enumeration Case Pattern) 
  6. 可選模式(Optional Pattern) 
  7. 類型轉換模式(Type-Casting Pattern) 
  8. 表達式模式(Expression Pattern)

通配符模式(Wildcard Pattern)

  • _ 比對任何值
  • _? 比對非nil值
enum Life {
    case human(name: String, age: Int?)
    case animal(name: String, age: Int?)
}

func check(_ life: Life) {
    switch life {
    case .human(let name, _):
        print("human", name)
    case .animal(let name, _?):
        print("animal", name)
    default:
        print("other")
    }
}

check(Life.human(name: "Rose", age: 20)) //human Rose
check(Life.human(name: "Jack", age: nil)) //human Jack
check(Life.animal(name: "Dog", age: 5)) //animal Dog
check(Life.animal(name: "Cat", age: nil)) //other

check(.human(name: "Rose", age: 20)) //human Rose
check(.human(name: "Jack", age: nil)) //human Jack
check(.animal(name: "Dog", age: 5)) //animal Dog
check(.animal(name: "Cat", age: nil)) //other
           

辨別符模式(Identifier Pattern)

  • 給對應的變量、常量名指派
var age = 10
let name = "jack"
           

值綁定模式(Value-Binding Pattern)

把元祖中3和2的值分别綁定給x和y:

Swift(學習):模式比對模式(Pattern)通配符模式(Wildcard Pattern)辨別符模式(Identifier Pattern)值綁定模式(Value-Binding Pattern)元組模式(Tuple Pattern)枚舉Case模式(Enumeration Case Pattern)可選模式(Optional Pattern)類型轉換模式(Type- Casting Pattern)表達式模式(Expression Pattern)自定義表達式模式Where

元組模式(Tuple Pattern)

let points = [(0, 0), (1, 0), (2, 0)]
for (x, _) in points {
    print(x)
}

let name: String? = "Jack"
let age = 18
let info: Any = [1,2]
switch (name, age, info) {
case (_?, _, _ as String):
    print("case")
default:
    print("default")
} //輸出default

var scores = ["jack": 98, "Rose": 100, "Kate": 86]
for (name, score) in scores {
    print((name, score))
}
//輸出:
//("jack", 98)
//("Rose", 100)
//("Kate", 86)
           

枚舉Case模式(Enumeration Case Pattern)

  • if case語句等價于隻有一個case的switch語句
let age = 2

//原來的寫法
if age >= 0 && age <= 9 {
    print("[0, 9]") //[0, 9]
}

//枚舉case模式:看age裡是否有0到9的數字,如果比對,進入{ }
if case 0...9 = age {
    print("[0, 9]") //[0, 9]
}

guard case 0...9 = age else { return }
print("[0, 9]")

switch age {
case 0...9: print("[0, 9]")
default: break
}//[0, 9]

let ages: [Int?] = [2, 3, nil, 5]
for case nil in ages {
    print("有nil值")
    break
} //有nil值

let points = [(1, 0), (2, 1), (3, 0)]
for case let (x, 0) in points {
    print(x)
} // 1 3
           

可選模式(Optional Pattern)

//.some(let x)等同于 let x?
let age: Int? = 42
if case .some(let x) = age {print(x)}
if case let x? = age { print(x)} //age為非空則比對成功,并且解包給x

let ages: [Int?] = [nil, 2, 3, nil, 5]
//age為不為nil的可選型,符合則自動解包
for case let age? in ages {
    print(age)
}

//下面的代碼與上面的代碼實作效果一緻
for item in ages {
    //item如果為非空可選,則自動解包指派給age
    if let age = item {
        print(age)
    }
}
           
func check(_ num: Int?) {
    switch num {
    case 2?: print("2") //如果num為非nil的可選型2,輸出2
    case 4?: print("4")
    case 6?: print("6")
    case _?: print("other")
    case _: print("nil")
    }
}

check(4) //4
check(8) //other
check(nil) //nil
           

類型轉換模式(Type- Casting Pattern)

let num = 6
switch num {
case is Int:
    //num是Int類型
    print("is Int", num)
default:
    break
} //輸出 is Int 6

let num1: Any = 6
switch num1 {
case is Int:
    //num依然是Any類型,但是Any是任意類型,可以認為是Int,是以會進入這個case
    print("is Int", num)
default:
    break
} //輸出 is Int 6
           
let num: Any = 6
switch num {
    //num如果可以轉換為Int類型,就把轉換後的值給n
case let n as Int:
    //num依然是Any類型,隻是它轉換後的n是Int類型
    print("as Int", n + 1)
default:
    break
} // 輸出 as Int 7
           

實際用例:

class Animal {
    func eat() {print(type(of: self), "eat")}
}

class Dog: Animal {
    func run() {
        print(type(of: self), "run")
    }
}

class Cat: Animal {
    func jump() {
        print(type(of: self), "jump")
    }
}

func check(_ animal: Animal) {
    switch animal {
        //看能否吧animal轉換為Dog類型,如果可以,則把轉換後的值給dog變量
    case let dog as Dog:
        dog.eat()
        dog.run()
    case is Cat:
        //編譯器認為現在的animal是Animal類型,隻能調用animal的eat()方法,不能調用Cat的jump方法
        animal.eat()
        //這裡的animal不能直接調用Cat的jump()方法,除非強制轉換成Cat類型
//        (animal as? Cat)?.jump()
    default:
        break
    }
}

check(Dog())
//Dog eat
//Dog run

check(Cat())
//typeof最終看調用的實際對象類型,是以是Cat類型
//Cat eat
           

表達式模式(Expression Pattern)

  • 表達模式用在case中
let point = (1, 2)
switch point {
case (0, 0):
    print("(0, 0) is at the origin.")
case(-2...2, -2...2):
    print("(\(point.0),\(point.1)) is near the origin.")
default:
    print("The point is at (\(point.0),\(point.1)).")
} //輸出:(1,2) is near the origin.
           

通果反彙編運算,我們可以看到這實際上是通過~=這個符号實作的表達式比對,是以想要自定義表達式模式比對,需要重載~=這個運算符

Swift(學習):模式比對模式(Pattern)通配符模式(Wildcard Pattern)辨別符模式(Identifier Pattern)值綁定模式(Value-Binding Pattern)元組模式(Tuple Pattern)枚舉Case模式(Enumeration Case Pattern)可選模式(Optional Pattern)類型轉換模式(Type- Casting Pattern)表達式模式(Expression Pattern)自定義表達式模式Where

自定義表達式模式

  • 可以通過重載運算符,自定義表達式模式的比對規則
struct Student {
    var score = 0, name = ""
    //pattern是case後的值
    //value是switch後的值
    static func ~= (pattern: Int, value: Student) -> Bool {
        return value.score >= pattern
    }
    static func ~= (pattern: ClosedRange<Int>, value: Student) -> Bool {
        return pattern.contains(value.score)
    }
    static func ~= (pattern: Range<Int>, value: Student) -> Bool {
        return pattern.contains(value.score)
    }
}

var stu  = Student(score: 75, name: "Jack")
switch stu {
case 100: print(">= 100")
case 90: print(">= 90")
case 80..<90: print("[80, 90]")
case 60...79: print("[60, 79]")
case 0: print(">= 0")
default: break
} //輸出:[60, 79]


一般情況下,寫如下代碼會報錯,但是當重載了表達式模式比對,就不會報錯:
if case 60 = stu {
    print(">= 60")
} //>= 60
           
var info = (Student(score: 70, name: "Jack"), "及格")
switch info {
//如下代碼表示Student(score: 70, name: "Jack")和60進行比對,"及格"和text進行比對,當score大于60則為true,走print(text)代碼
case let (60, text): print(text)
default: break
} //輸出: 及格
           

先列舉一個String判斷開頭結尾是什麼的複雜結構的正常代碼:

//prefix == "21"
//str == "123456"
func hasPerfix(_ prefix: String) -> ((String) -> Bool) {
    return {
        (str: String) -> Bool in
        str.hasPrefix(prefix)
    }
}

//suffix == "456"
//str == "123456"
func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
    return {
        (str: String) -> Bool in
        str.hasSuffix(suffix)
    }
}

var fn = hasPerfix("12")
print(fn("123456")) //true
var fn1 = hasSuffix("456")
print(fn1("123456")) //true
           

接下來用重載運算符的方式,自定義表達式模式的比對規則:

extension String {
    static func ~= (pattern: (String) -> Bool, value: String) -> Bool {
       return pattern(value)
    }
}

func hasPerfix(_ prefix: String) -> ((String) -> Bool) {
//$0表示第一個參數
   return { $0.hasPrefix(prefix) }
}
func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
    return { $0.hasSuffix(suffix) }
}

var str = "123456"
switch str {
case hasPerfix("12"), hasSuffix("456"):
    print("以12開頭或者以456結尾")
default:
    break
} // 輸出:以12開頭或者以456結尾

//var str = "123456"
//switch str {
//case hasPerfix("12"):
//    print("以12開頭")
//case hasSuffix("456"):
//    print("以456結尾")
//default:
//    break
//} //輸出:以12開頭
           

類似上面的例子:

Swift(學習):模式比對模式(Pattern)通配符模式(Wildcard Pattern)辨別符模式(Identifier Pattern)值綁定模式(Value-Binding Pattern)元組模式(Tuple Pattern)枚舉Case模式(Enumeration Case Pattern)可選模式(Optional Pattern)類型轉換模式(Type- Casting Pattern)表達式模式(Expression Pattern)自定義表達式模式Where
  • 接下來列舉一個重載運算符實作新的運算符功能的例子:

1.  原始寫法:

func greaterThan(_ num: Int) -> (Int) -> Bool {
    return {
        (i: Int) -> Bool in
        return i > num
    }
}

var fn = greaterThan(5)
print(fn(10)) //true
           

2.  自定義表達模式的比對原則:

extension Int {
    static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
        return pattern(value)
    }
}

func greaterThan1(_ num: Int) -> (Int) -> Bool {
    return { $0 > num }
}

var age = 10

switch age {
case greaterThan(5):
    print(age, "大于5")
default: break
} // 輸出:10 大于5
           

3.  重寫比較運算符

extension Int {
    static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
        return pattern(value)
    }
}

prefix operator ~>
prefix operator ~>=
prefix operator ~<
prefix operator ~<=
prefix func ~> (_ i: Int) -> ((Int) -> Bool) { return { $0 > i} }
prefix func ~>= (_ i: Int) -> ((Int) -> Bool) { return { $0 >= i} }
prefix func ~< (_ i: Int) -> ((Int) -> Bool) { return { $0 < i} }
prefix func ~<= (_ i: Int) -> ((Int) -> Bool) { return { $0 <= i} }

var age = 9
switch age {
case ~>=0:
    print("1")
case ~>10:
print("2")
default:
     break
} //輸出:1
           
  • 在列舉一個簡單奇偶數判定的例子
func isEven(_ i: Int) -> Bool { return i % 2 == 0}
func isOdd(_ i: Int) -> Bool { return i % 2 != 0}

extension Int {
    static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
       return pattern(value)
    }
}

var age = 11
switch age {
case isEven:
    print("偶數")
case isOdd:
    print("奇數")
default:
    print("其他")
} // 輸出: 奇數
           

Where

  • 可以使用where為模式比對增加條件

switch case中的where用例:

var data = (10, "jack")
switch data {
case let (age, _) where age > 10:
    print(data.1, "age>10")
case let (age, _) where age > 0:
    print(data.1, "age>0")
default:
    break
} //jack age>0
           

for循環中的where用例:

var ages = [10, 20 , 44, 23, 55]
for age in ages where  age > 30 {
    print(age)
} //44 55
           

協定中關聯類型的where用例:

protocol Stackable { associatedtype Element}
protocol Container {
    associatedtype Stack : Stackable where Stack.Element : Equatable
}
           

泛型中的where用例:

func equal<S1: Stackable, S2:Stackable>(_ s1:S1, _s2:S2) -> Bool where S1.Element == S2.Element, S1.Element : Hashable{
    return false
}
           

擴充中的where用例:

extension Container where Self.Stack.Element : Hashable { }