一. 字面量(Literal)
下面代碼中的10、false、"Jack"都是字面量
var age = 10
var isRed = false
var name = "Jack"
Swift源碼規(guī)定,常見(jiàn)字面量的默認(rèn)類(lèi)型:
public typealias IntegerLiteralType = Int
public typealias FloatLiteralType = Double
public typealias BooleanLiteralType = Bool
public typealias StringLiteralType = String
可以通過(guò)typealias修改字面量的默認(rèn)類(lèi)型
typealias FloatLiteralType = Float
typealias IntegerLiteralType = UInt8
var age = 10 // UInt8
var height = 1.68 // Float
Swift自帶的絕大部分類(lèi)型,都支持直接通過(guò)字面量進(jìn)行初始化,如下:
Bool、Int、Float、Double、String、Array、Dictionary、Set、Optional等
1. 字面量協(xié)議
Swift自帶類(lèi)型之所以能夠通過(guò)字面量初始化,是因?yàn)樗鼈冏袷亓藢?duì)應(yīng)的協(xié)議
- 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. 字面量協(xié)議的應(yīng)用
讓Int類(lèi)型遵守ExpressibleByBooleanLiteral協(xié)議,這樣就能通過(guò)Bool字面量來(lái)初始化Int類(lèi)型數(shù)據(jù)
//有點(diǎn)類(lèi)似于C++中的轉(zhuǎn)換構(gòu)造函數(shù)
extension Int : ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = value ? 1 : 0
}
}
var num: Int = true //通過(guò)Bool字面量來(lái)初始化Int類(lèi)型數(shù)據(jù)
print(num) // 1
使用Int、Double、String類(lèi)型字面量來(lái)初始化Student對(duì)象
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
使?數(shù)組、字典字?量初始化Point
struct Point {
var x = 0.0, y = 0.0
}
extension Point : ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
init(arrayLiteral elements: Double...) { //使用數(shù)組初始化
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)?
模式是用于匹配的規(guī)則,比如switch的case、捕捉錯(cuò)誤的catch、if/guard/while/for語(yǔ)句的條件等。
Swift中的模式有:
- 通配符模式(Wildcard Pattern)
- 標(biāo)識(shí)符模式(Identifier Pattern)
- 值綁定模式(Value-Binding Pattern)
- 元組模式(Tuple Pattern)
- 枚舉Case模式(Enumeration Case Pattern)
- 可選模式(Optional Pattern)
- 類(lèi)型轉(zhuǎn)換模式(Type-Casting Pattern)
- 表達(dá)式模式(Expression Pattern)
1. 通配符模式(Wildcard Pattern)
_ 匹配任何值
_? 匹配非nil值
enum Life {
case human(name: String, age: Int?)
case animal(name: String, age: Int?)
}
func check(_ life: Life) { //這里的_是省略標(biāo)簽
switch life {
case .human(let name, _): //第二個(gè)可以是任何值
print("human", name)
case .animal(let name, _?): //要求第二個(gè)是非空
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. 標(biāo)識(shí)符模式(Identifier Pattern)
給對(duì)應(yīng)的變量、常量名賦值
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 { //第二個(gè)可以是任何值
print(x)
}
let name: String? = "jack"
let age = 18
let info: Any = [1, 2]
switch (name, age, info) {
//要求,第一個(gè)非空值,第二個(gè)任何值,第三個(gè)是可以轉(zhuǎn)成String的值,第三個(gè)不符合,所以匹配失敗,打印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)
原來(lái)的寫(xiě)法:
let age = 2
if age >= 0 && age <= 9 {
print("[0, 9]")
}
使用switch:
switch age {
case 0...9:
print("[0, 9]")
default:
break
}
if case語(yǔ)句等價(jià)于只有一個(gè)case的switch語(yǔ)句:
if case 0...9 = age {
print("[0, 9]")
}
同理使用guard case:
guard case 0...9 = age else { return }
print("[0, 9]")
擴(kuò)展使用for case,原來(lái)的寫(xiě)法如下:
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后代碼如下,這樣寫(xiě)的代碼更具Swift風(fēng)格。
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:現(xiàn)在我們知道了,除了switch case,if case、for case也都有了??
6. 可選模式(Optional Pattern)
以前我們這么寫(xiě):
let ages: [Int?] = [nil, 2, 3, nil, 5]
for item in ages { //item是可選項(xiàng)
if let age = item { //可選項(xiàng)綁定
print(age)
}
} // 2 3 5
使用for case之后我們可以這么寫(xiě):
let ages: [Int?] = [nil, 2, 3, nil, 5]
for case let age? in ages { //取出每一個(gè)可選項(xiàng),如果可選項(xiàng)綁定給age成功,則會(huì)執(zhí)行大括號(hào)的代碼
print(age) //這時(shí)候age一定有值
} //2 3 5
使用switch判斷可選項(xiàng)的值,原來(lái)我們這么寫(xiě):
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
如果寫(xiě)成如下方式,是不是更加簡(jiǎn)潔更加Swift風(fēng)格呢?
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. 類(lèi)型轉(zhuǎn)換模式(Type-Casting Pattern)
let num: Any = 6
switch num {
case is Int: //判斷num是否是Int類(lèi)型
//上面僅僅是判斷num是否是Int類(lèi)型,編譯器并沒(méi)有進(jìn)行強(qiáng)轉(zhuǎn),編譯器依然認(rèn)為num是Any類(lèi)型
print("is Int", num)
case let n as Int: //判斷能不能將num強(qiáng)轉(zhuǎn)成Int,如果可以就強(qiáng)轉(zhuǎn),然后賦值給n,最后n是Int類(lèi)型,num還是Any類(lèi)型
print("as Int",n)
default:
break
}
//type(of: self)可以獲取當(dāng)前方法調(diào)用者是誰(shuí)
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: //傳進(jìn)來(lái)是Animal類(lèi)型,強(qiáng)轉(zhuǎn)成Dog,下?兩個(gè)?法就可以調(diào)
dog.eat()
dog.run()
case is Cat:
//傳進(jìn)來(lái)是Animal類(lèi)型,沒(méi)強(qiáng)轉(zhuǎn)成Cat,編譯器認(rèn)為還是Animal,只能調(diào)eat,最終實(shí)際調(diào)?的還是Cat的eat?法
animal.eat() //如果真想調(diào)?jump只能強(qiáng)轉(zhuǎn):(animal as? Cat)?.jump()
default: break
}
}
// Dog eat
// Dog run
check(Dog())
// Cat eat
check(Cat())
8. 表達(dá)式模式(Expression Pattern)
表達(dá)式模式用在switch case中,簡(jiǎn)單的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.
復(fù)雜的case匹配??其實(shí)調(diào)?了~=運(yùn)算符來(lái)匹配,我們可以重載~=運(yùn)算符來(lái)重新定制匹配規(guī)則,如下:
① ?定義Student和Int的匹配規(guī)則
value:switch后面的內(nèi)容,pattern:case后面的內(nèi)容。
struct Student { var score = 0, name = ""
//?定義Student和Int的匹配規(guī)則
static func ~= (pattern: Int, value: Student) -> Bool { value.score >= pattern }
//?定義Student和閉區(qū)間的匹配規(guī)則
static func ~= (pattern: ClosedRange<Int>, value: Student) -> Bool { pattern.contains(value.score) }
//?定義Student和開(kāi)區(qū)間的匹配規(guī)則
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]
上面說(shuō)過(guò):if case語(yǔ)句等價(jià)于只有1個(gè)case的switch語(yǔ)句,所以也可以這么寫(xiě):
if case 60 = stu { //將student對(duì)象和60匹配
print(">= 60")
} // >= 60
把Student對(duì)象放到元祖里面,這時(shí)候就是把Student和60匹配,如果匹配成功就將及格和text綁定,如下:
var info = (Student(score: 70, name: "Jack"), "及格")
switch info {
case let (60, text): print(text) //如果匹配成功就將及格和text綁定
default: break
} // 及格
② ?定義String和函數(shù)(帶參數(shù))的匹配規(guī)則
extension String {
static func ~= (pattern: (String) -> Bool, value: String) -> Bool {
pattern(value) //調(diào)用一下這個(gè)函數(shù),將value傳進(jìn)去
}
}
//接收一個(gè)String返回一個(gè)函數(shù)
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"): //兩個(gè)條件只需要滿(mǎn)足一個(gè)
print("以j開(kāi)頭或者以k結(jié)尾")
default: break
} //以j開(kāi)頭或者以k結(jié)尾
所以重寫(xiě)~=把str和函數(shù)進(jìn)?匹配,這樣只是學(xué)習(xí)怎么?定義表達(dá)式模式,其實(shí)使?系統(tǒng)的那兩個(gè)函數(shù)更簡(jiǎn)單。
上面的hasPrefix、hasSuffix?法是傳??個(gè)prefix,return?個(gè)函數(shù),只不過(guò)上面是簡(jiǎn)寫(xiě)的,完整寫(xiě)法如下:
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和函數(shù)的匹配規(guī)則
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("偶數(shù)")
case isOdd:
print("奇數(shù)")
default:
print("其他")
}
④ ?定義Int和?定義運(yùn)算符的匹配規(guī)則
這個(gè)例?和示例3本質(zhì)是?樣的,因?yàn)檫\(yùn)算符的本質(zhì)也是函數(shù)
prefix operator ~>
prefix operator ~>=
prefix operator ~<
prefix operator ~<=
extension Int {
static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
return
pattern(value) //調(diào)用一下這個(gè)函數(shù),將value傳進(jìn)去
}
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. 補(bǔ)充: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循環(huán)后面:
var ages = [10, 20, 44, 23, 55]
for age in ages where age > 30 {
print(age)
} // 44 55
在關(guān)聯(lián)類(lèi)型后面:
protocol Stackable { associatedtype Element }
protocol Container {
associatedtype Stack : Stackable where Stack.Element : Equatable
}
在函數(shù)返回值后面給泛型做一些約束:
func equal<S1: Stackable, S2: Stackable>(_ s1: S1, _ s2: S2) -> Bool
where S1.Element == S2.Element, S1.Element : Hashable {
return false
}
帶條件的協(xié)議的擴(kuò)展:
extension Container where Self.Stack.Element : Hashable { }