匹配模式(Pattern)
2019-08-05 本文已影响0人
曹来东
什么是模式?
模式是用于匹配的规则,比如
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)
}
}
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(.human(name: "Cat", age: nil))//human Cat
标识符模式 (Identifier Pattern )
- 给对应的变量 常量名赋值
var age = 10
let name = "Jack"
值绑定模式(Value-Binding Pattern)
let Point = (3,2)
switch Point {
case let (x,y):
print("The Point is at (\(x),\(y))." )
}
元祖模式(Tuple Pattern)
let points = [(0,0),(1,0),(2,0)]
for (x, _) in points {
print(x)//0 1 2
}
let name: String? = "jack"
let age = 18
let info: Any = [1,2]
switch (name, age, info) {//_? 匹配非nil
case (_?, _ , _ as String):
print("case")
default:
print("default")
}//default
枚举Case模式(Enumeration Case Pttern)
-
if case
语句等价于只有一个case
的switch
语句
let age = 2
//原来写法
if age >= 0 && age <= 9{
print("0...9")
}
//枚举case
if case 0...9 = age {
print("0...9")
}
guard case 0...9 = age else {
return//Return invalid outside of a func
}
print("0...9")
var age = 2
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)
let age: Int? = 42
if case .some(let x) = age {
print(x)//42
}
if case let x? = age {//x?匹配不为nil.如果x不为nil,并进行解包
print(x)//42
}
let ages: [Int?] = [nil, Optional(2), 3, nil, 5]
for case let age? in ages {//age?匹配不为nil.如果age不为nil.并进行解包
print(age)
}//2,3,5
for item in ages {
if let age = item {
print(age)
}
}//和上面的for循环效果是等价的
func check(_ num: Int?) {
switch num {
case 2?:
print("2")
case 4?:
print("4")
case 6?:
print("6")
case _?://匹配不为nil
print("Other")
case _:
print("nil")
}
}
check(4)//4
check(8)//other
check(nil)//nil
func check(_ num: Int?) {
switch num {
case _?://匹配不为nil
print("Other")
case 2?://Case will never be executed
print("2")
case 4?://Case will never be executed
print("4")
case 6?://Case will never be executed
print("6")
case _://匹配nil情况
print("nil")
}
}
check(4)//Other
check(8)//other
check(nil)//nil
类型转换模式(Type-Casting Pattern)
let num: Any = 6
switch num {
case is Int://编译器认为num 是Any类型
print("Is Int",num)
//与上面写法等价的
case let n as Int://Case will never be executed
print("as Int",n+1)
default:
print("default")
}
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 {
case let dog as Dog:
dog.eat()
dog.run()
case is Cat:
animal.eat()
default:
break
}
}
//Dog eat
//Dog run
check(Dog())
check(Cat())//Cat eat
表达式模式(Expression Pattern)
- 表达式模式用在
case
中
let point = (1,2)
switch point {
case (0,0):
print(point)
case (-2...2,-2...2):
print(point)
print("-2...2,-2...2")
default:
print(point)
}//(1, 2) -2...2,-2...2
自定义表达式模式
- 可以通过重载运算符,自定义表达式模式的匹配规则
struct Student {
var score = 0, name = ""
static func ~= (pattern: Int, value: Student) -> Bool {
value.score >= pattern
}
static func ~= (pattern: ClosedRange<Int>, value: Student) -> Bool {
pattern.contains(value.score)
}
static func ~= (pattern: Range<Int>, value: Student) -> Bool {
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 {
case let (60, text): print(text)
default: break
}//及格
extension String {
static func ~= (pattern: (String) -> Bool, value: String) -> Bool {
pattern(value)
}
}
func hasPrefix(_ prefix: String) -> ((String) -> Bool) {
{ $0.hasPrefix(prefix) }
}
func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
{ $0.hasSuffix(suffix) }
}
var str = "jack"
switch str {
case hasPrefix("j"), hasSuffix("k"):
print("以j开头,以k结尾")
default:
break
}//以j开头,以k结尾
func isEven(_ i: Int) -> Bool {
i % 2 == 0
}
func isOdd(_ i: Int) -> Bool {
i % 2 != 0
}
extension Int {
static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
pattern(value)
}
}
var age = 9
switch age {
case isEven:
print("偶数")
case isOdd:
print("奇数")
default:
print("其他")
}
prefix operator ~>
prefix operator ~>=
prefix operator ~<
prefix operator ~<=
prefix func ~> (_ i: Int) -> ((Int) -> Bool){
{
$0 > i
}
}
prefix func ~>= (_ i: Int) -> ((Int) -> Bool) {
{ $0 >= i }
}
prefix func ~< (_ i: Int) -> ((Int) -> Bool){
{ $0 < i }
}
prefix func ~<= (_ i: Int) -> ((Int) -> Bool) {
{
$0 <= i
}
}
var age = 9
switch age {
//Expression pattern of type '(Int) -> Bool' cannot match values of type 'Int'
case ~>=0:
print("1")
//Expression pattern of type '(Int) -> Bool' cannot match values of type 'Int'
case ~>10:
print("2")
default:
break
}
where
可以使用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
var ages = [10,20,44,23,55]
for age in ages where age > 30 {
print(age)
}//44 55
protocol Stackable {
associatedtype Element
}
protocol Container {
associatedtype Stack : Stackable where Stack.Element : Equatable
}
func equal<S1: Stackable ,S2: Stackable>(_ s1: S1, _ s2: S2) -> Bool where S1.Element == S2.Element, S1.Element: Hashable {
return false
}
extension Container where Self.Stack.Element : Hashable {}