注意:
必須將延遲存儲屬性聲明成變量(使用var關(guān)鍵字),因?yàn)閷傩缘闹翟趯?shí)例構(gòu)造完成之前可能無法得到。而常量屬性在構(gòu)造過程完成之前必須要有初始值,因此無法聲明成延遲屬性。
延遲存儲屬性一般用于:
- 延遲對象的創(chuàng)建。
- 當(dāng)屬性的值依賴于其他未知類
class sample {
lazy var no = number()
}
class number {
var name = "Apple"
}
var firstSample = sample()
print(firstSample.no.name)
屬性觀察器監(jiān)控和響應(yīng)屬性值的變化,每次屬性被設(shè)置值的時(shí)候都會調(diào)用屬性觀察器,甚至新的值和現(xiàn)在的值相同的時(shí)候也不例外。
可以為除了延遲存儲屬性之外的其他存儲屬性添加屬性觀察器,也可以通過重載屬性的方式為繼承的屬性(包括存儲屬性和計(jì)算屬性)添加屬性觀察器。
注意:
不需要為無法重載的計(jì)算屬性添加屬性觀察器,因?yàn)榭梢酝ㄟ^setter直接監(jiān)控和響應(yīng)值的變化。
可以為屬性添加如下的一個(gè)或全部觀察器:
- willSet在設(shè)置新的值之前調(diào)用。
- didSet在新的值被設(shè)置之后立即調(diào)用。
- willSet和didSet觀察器在屬性初始化過程中不會被調(diào)用。
class Samplepgm {
var counter : Int = 0 {
willSet(newTotal) {
print("計(jì)數(shù)器:\(newTotal)")
}
didSet {
if counter > oldValue {
print("新增數(shù)\(counter - oldValue)")
}
}
}
}
let NewCounter = Samplepgm()
NewCounter.counter = 100
NewCounter.counter = 800
//輸出結(jié)果
計(jì)數(shù)器:100
新增數(shù):100
計(jì)數(shù)器:800
新增數(shù):700
var name = ""
name.isEmpty //ture 字符串判空
let str:Character = "A" //ture
let str:Character = "AB" //false
字符串拼接 插入

image.png
字符串比較

image.png
字符串截取

image.png
數(shù)組過濾器

image.png
var dictionary1 = ["key1": 8, "key2": 1,"key3": 4,"key4": 9,"key5": 5,"key6": 2,"key7": 6]
let values = dictionary1.values.sorted()
//print("values") = [1, 2, 4, 5, 6, 8, 9]
dictionary1.updateValue(10, forKey: "key1")
//["key6": 2, "key3": 4, "key1": 10, "key2": 1, "key4": 9, "key7": 6, "key5": 5]
dictionary1.updateValue(3, forKey: "key8")
//["key6": 2, "key3": 4, "key1": 10, "key2": 1, "key8": 3, "key4": 9, "key7": 6, "key5": 5]
dictionary1.removeAll() // 刪除所有元素
dictionary1.removeValue(forKey: "key1") // 通過查找key來刪除元素
let index = dictionary1.index(dictionary1.startIndex, offsetBy: 1)
dictionary1.remove(at: index) // 通過下標(biāo)刪除元素,offsetBy是第幾個(gè)元素