Swift 基础知识 持续更新

2018-11-05  本文已影响0人  coder袁

\color{red}{懒加载}

注意:

必须将延迟存储属性声明成变量(使用var关键字),因为属性的值在实例构造完成之前可能无法得到。而常量属性在构造过程完成之前必须要有初始值,因此无法声明成延迟属性。

延迟存储属性一般用于:
class sample {
    lazy var no = number()
}
class number {
    var name = "Apple"
}
var firstSample = sample()
print(firstSample.no.name)

\color{red}{属性观察器}

属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察器,甚至新的值和现在的值相同的时候也不例外。
可以为除了延迟存储属性之外的其他存储属性添加属性观察器,也可以通过重载属性的方式为继承的属性(包括存储属性和计算属性)添加属性观察器。
注意:
不需要为无法重载的计算属性添加属性观察器,因为可以通过setter直接监控和响应值的变化。

可以为属性添加如下的一个或全部观察器:
class Samplepgm {
    var counter : Int = 0 {
        willSet(newTotal) {
            print("计数器:\(newTotal)")
        }
        didSet {
            if counter > oldValue {
                print("新增数\(counter - oldValue)")
            }
        }
    }
}
let NewCounter = Samplepgm()
NewCounter.counter = 100
NewCounter.counter = 800
//输出结果
计数器:100
新增数:100
计数器:800
新增数:700

\color{red}{字符串}

var name = ""
name.isEmpty //ture 字符串判空

let str:Character = "A" //ture
let str:Character = "AB" //false

字符串拼接 插入
image.png
字符串比较
image.png
字符串截取
image.png

\color{red}{数组}

数组过滤器
image.png

\color{red}{字典}

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) // 通过下标删除元素,offsetBy是第几个元素
上一篇下一篇

猜你喜欢

热点阅读