iOS-Swift-字面量、模式匹配

一. 字面量(Literal)

下面代码中的10、false、"Jack"都是字面量

var age = 10
var isRed = false
var name = "Jack"

Swift源码规定,常见字面量的默认类型:

public typealias IntegerLiteralType = Int
public typealias FloatLiteralType = Double
public typealias BooleanLiteralType = Bool
public typealias StringLiteralType = String

可以通过typealias修改字面量的默认类型

typealias FloatLiteralType = Float
typealias IntegerLiteralType = UInt8
var age = 10 // UInt8
var height = 1.68 // Float

Swift自带的绝大部分类型,都支持直接通过字面量进行初始化,如下:

Bool、Int、Float、Double、String、Array、Dictionary、Set、Optional等

1. 字面量协议

Swift自带类型之所以能够通过字面量初始化,是因为它们遵守了对应的协议

  • Bool : ExpressibleByBooleanLiteral
  • Int : ExpressibleByIntegerLiteral
  • Float、Double : ExpressibleByIntegerLiteral、ExpressibleByFloatLiteral
  • Dictionary : ExpressibleByDictionaryLiteral
  • String : ExpressibleByStringLiteral
  • Array、Set : ExpressibleByArrayLiteral
  • Optional : ExpressibleByNilLiteral
var b: Bool = false // ExpressibleByBooleanLiteral
var i: Int = 10 // ExpressibleByIntegerLiteral
var f0: Float = 10 // ExpressibleByIntegerLiteral
var f1: Float = 10.0 // ExpressibleByFloatLiteral
var d0: Double = 10 // ExpressibleByIntegerLiteral
var d1: Double = 10.0 // ExpressibleByFloatLiteral
var s: String = "jack" // ExpressibleByStringLiteral
var arr: Array = [1, 2, 3] // ExpressibleByArrayLiteral
var set: Set = [1, 2, 3] // ExpressibleByArrayLiteral
var dict: Dictionary = ["jack" : 60] // ExpressibleByDictionaryLiteral
var o: Optional<Int> = nil // ExpressibleByNilLiteral

2. 字面量协议的应用

让Int类型遵守ExpressibleByBooleanLiteral协议,这样就能通过Bool字面量来初始化Int类型数据

//有点类似于C++中的转换构造函数
extension Int : ExpressibleByBooleanLiteral {
    public init(booleanLiteral value: Bool) {
        self = value ? 1 : 0
    }
}
var num: Int = true //通过Bool字面量来初始化Int类型数据
print(num) // 1

使用Int、Double、String类型字面量来初始化Student对象

class Student : ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByStringLiteral, CustomStringConvertible {
    var name: String = ""
    var score: Double = 0
    required init(floatLiteral value: Double) { self.score = value }
    required init(integerLiteral value: Int) { self.score = Double(value) }
    required init(stringLiteral value: String) { self.name = value } //使用一般String
    required init(unicodeScalarLiteral value: String) { self.name = value } //unicode表情
    required init(extendedGraphemeClusterLiteral value: String) { self.name = value } //特殊字符
    var description: String { "name=\(name),score=\(score)" }
}
var stu: Student = 90
print(stu) // name=,score=90.0
stu = 98.5
print(stu) // name=,score=98.5
stu = "Jack"
print(stu) // name=Jack,score=0.0

使⽤数组、字典字⾯量初始化Point

struct Point {
    var x = 0.0, y = 0.0
}
extension Point : ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { 
    init(arrayLiteral elements: Double...) { //使用数组初始化
    guard elements.count > 0 else { return }
    self.x = elements[0]
    guard elements.count > 1 else { return }
    self.y = elements[1]
}
    init(dictionaryLiteral elements: (String, Double)...) { //使用字典初始化
        for (k, v) in elements {
            if k == "x" { self.x = v }
            else if k == "y" { self.y = v }
        }
    }
}
var p: Point = [10.5, 20.5]
print(p) // Point(x: 10.5, y: 20.5)
p = ["x" : 11, "y" : 22]
print(p) // Point(x: 11.0, y: 22.0)

二. 模式匹配

什么是模式(Pattern)?
模式是用于匹配的规则,比如switch的case、捕捉错误的catch、if/guard/while/for语句的条件等。

Swift中的模式有:

  • 通配符模式(Wildcard Pattern)
  • 标识符模式(Identifier Pattern)
  • 值绑定模式(Value-Binding Pattern)
  • 元组模式(Tuple Pattern)
  • 枚举Case模式(Enumeration Case Pattern)
  • 可选模式(Optional Pattern)
  • 类型转换模式(Type-Casting Pattern)
  • 表达式模式(Expression Pattern)

1. 通配符模式(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(.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

2. 标识符模式(Identifier Pattern)

给对应的变量、常量名赋值

var age = 10 
let name = "jack"

3. 值绑定模式(Value-Binding Pattern)

let point = (3, 2)
switch point {
case let (x, y):
    print("The point is at (\(x), \(y)).")
}

4. 元组模式(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) {
    //要求,第一个非空值,第二个任何值,第三个是可以转成String的值,第三个不符合,所以匹配失败,打印default
    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)
}

5. 枚举Case模式(Enumeration Case Pattern)

原来的写法:

let age = 2
if age >= 0 && age <= 9 {
    print("[0, 9]")
}

使用switch:

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

if case语句等价于只有一个case的switch语句:

if case 0...9 = age {
    print("[0, 9]")
}

同理使用guard case:

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

扩展使用for case,原来的写法如下:

let ages: [Int?] = [2, 3, nil, 5]
for age in ages {
    if age == nil { //匹配nil值
        print("有nil值")
    }
    break
} //有nil值
 
let points = [(1, 0), (2, 1), (3, 0)]
for (x, y) in points {
    if y == 0 {
        print(x)
    }
} //1 3

使用for case后代码如下,这样写的代码更具Swift风格。

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

Tips:现在我们知道了,除了switch case,if case、for case也都有了😜

6. 可选模式(Optional Pattern)

以前我们这么写:

let ages: [Int?] = [nil, 2, 3, nil, 5]
for item in ages { //item是可选项
    if let age = item { //可选项绑定
        print(age)
    }
} // 2 3 5

使用for case之后我们可以这么写:

let ages: [Int?] = [nil, 2, 3, nil, 5]
for case let age? in ages { //取出每一个可选项,如果可选项绑定给age成功,则会执行大括号的代码
    print(age) //这时候age一定有值
} //2 3 5

使用switch判断可选项的值,原来我们这么写:

func check(_ num: Int?) {
    if let x = num {
        switch x {
        case 2:
            print("2") //非空2
        case 4:
            print("4") //非空4
        case 6:
            print("6") //非空6
        default:
            print("other") //非空其他值
        }
    } else {
        print("nil") //空
    }
}
check(4) // 4
check(8) // other
check(nil) // nil

如果写成如下方式,是不是更加简洁更加Swift风格呢?

func check(_ num: Int?) {
    switch num {
        case 2?: print("2") //非空2
        case 4?: print("4") //非空4
        case 6?: print("6") //非空6
        case _?: print("other") //非空其他值
        case nil: print("nil")  //空
    }
}
check(4) // 4
check(8) // other
check(nil) // nil

7. 类型转换模式(Type-Casting Pattern)

let num: Any = 6
switch num {
    case is Int: //判断num是否是Int类型
      //上面仅仅是判断num是否是Int类型,编译器并没有进行强转,编译器依然认为num是Any类型
      print("is Int", num) 
    case let n as Int: //判断能不能将num强转成Int,如果可以就强转,然后赋值给n,最后n是Int类型,num还是Any类型
      print("as Int",n) 
    default:
      break
}
//type(of: self)可以获取当前方法调用者是谁
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: //传进来是Animal类型,强转成Dog,下⾯两个⽅法就可以调
        dog.eat()
        dog.run()
    case is Cat:
        //传进来是Animal类型,没强转成Cat,编译器认为还是Animal,只能调eat,最终实际调⽤的还是Cat的eat⽅法
        animal.eat() //如果真想调⽤jump只能强转:(animal as? Cat)?.jump()
        default: break
    }
}
// Dog eat
// Dog run
check(Dog())
// Cat eat
check(Cat())

8. 表达式模式(Expression Pattern)

表达式模式用在switch case中,简单的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.

复杂的case匹配⾥⾯其实调⽤了~=运算符来匹配,我们可以重载~=运算符来重新定制匹配规则,如下:

① ⾃定义Student和Int的匹配规则

value:switch后面的内容,pattern:case后面的内容。

struct Student { var score = 0, name = ""
    //⾃定义Student和Int的匹配规则
    static func ~= (pattern: Int, value: Student) -> Bool { value.score >= pattern }
    //⾃定义Student和闭区间的匹配规则
    static func ~= (pattern: ClosedRange<Int>, value: Student) -> Bool { pattern.contains(value.score) }
    //⾃定义Student和开区间的匹配规则
    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语句等价于只有1个case的switch语句,所以也可以这么写:

if case 60 = stu { //将student对象和60匹配
    print(">= 60")
} // >= 60

把Student对象放到元祖里面,这时候就是把Student和60匹配,如果匹配成功就将及格和text绑定,如下:

var info = (Student(score: 70, name: "Jack"), "及格")
switch info {
   case let (60, text): print(text) //如果匹配成功就将及格和text绑定
   default: break
} // 及格

② ⾃定义String和函数(带参数)的匹配规则

extension String {
    static func ~= (pattern: (String) -> Bool, value: String) -> Bool {
        pattern(value) //调用一下这个函数,将value传进去
    }
}

//接收一个String返回一个函数
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结尾

所以重写~=把str和函数进⾏匹配,这样只是学习怎么⾃定义表达式模式,其实使⽤系统的那两个函数更简单。

上面的hasPrefix、hasSuffix⽅法是传⼊⼀个prefix,return⼀个函数,只不过上面是简写的,完整写法如下:

func hasPrefix(_ prefix: String) -> ((String) -> Bool) {
    return {
    (str:String) -> Bool in
    str.hasPrefix(prefix)
    }
}

func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
    return {
    (str:String) -> Bool in
    str.hasSuffix(suffix)
    }
}

③ ⾃定义Int和函数的匹配规则

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("其他")
}

④ ⾃定义Int和⾃定义运算符的匹配规则

这个例⼦和示例3本质是⼀样的,因为运算符的本质也是函数

prefix operator ~>
prefix operator ~>=
prefix operator ~<
prefix operator ~<=

extension Int {
    static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
        return
        pattern(value) //调用一下这个函数,将value传进去
    }
    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 = 15
switch age {
case ~<=0:
    print("1")
case ~>10:
    print("2")
default: break
} // 2

9. 补充:where

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

在case后面:

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
}

在for循环后面:

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 { }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,002评论 6 509
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,777评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,341评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,085评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,110评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,868评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,528评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,422评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,938评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,067评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,199评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,877评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,540评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,079评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,192评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,514评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,190评论 2 357

推荐阅读更多精彩内容