swift从入门到精通20-模式匹配

208 阅读1分钟

1.通配符模式

_ 表示可匹配任何值。

?表示匹配非nil值。

例子:

enum Person {
    case sutdent(name: String,age: Int?)
    case teacher(name: String,age: Int?)
}


func text1(p: Person) {
    switch p {
    case .sutdent(let name, _):
        print("student",name)
    case .teacher(let name, _?):
        print("teacher",name)
    default:
        print("other")
    }
}


var p1 = Person.sutdent(name: "p1", age: 10)
var p2 = Person.sutdent(name: "p2", age: nil)
var p3 = Person.teacher(name: "p3", age: 20)
var p4 = Person.teacher(name: "p4", age: nil)
text1(p: p1)
text1(p: p2)
text1(p: p3)
text1(p: p4)

2.标识符模式

给对应的变量,常量赋值。

3.值绑定模式

let point = (1, 2)
switch point {
case let (x ,y):
    print(x,y)
default:
    break
}

4.元组模式

var scrores = ["A":"100","B":"80","C":"70"]
for (name,scroe) in scrores {
    print("name",name,"scroe",scroe)
}

5.枚举Case模式

let scroe = 2
if case 0...5 = scroe {
    print(scroe)
}

6.可选模式

let scroe: Int? = 2
if case let x? = scroe {
    print(x)
}

7.类型转换模式

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


class Dog: Animal {
    func run(){print("Dog run")}
}


class Cat: Animal {
    func jump(){print("Cat jump")}
}


func cheak(animal: Animal) {
    switch animal {
    case let dog as Dog:
        dog.eat()
        dog.run()
    case is Cat:
        animal.eat()
    default:
        break
    }
}


cheak(animal: Dog())
cheak(animal: Cat())

8.表达式模式

let point = (1, 2)
switch point {
case (0, 0):
    print("0 , 0")
case (1...3, 2...5):
    print(point.0, point.1)
default:
    print("other")
}

9.where

使用where为模式匹配增加匹配条件。

let point = (1, 2)
switch point {
case let (x, y) where x > 0 && y > 0:
        print(x,y)
    default:
        print("other")
}


上一篇文章:swift从入门到精通19-字面量