使用
\
訪問對象key path
struct Person {
var name:String
}
struct Book {
var title:String
var authors:[Person]
var primaryAuthor:Person {
return authors.first!
}
}
let jobs = Person(name: "Steve Jobs")
let gates = Person(name: "Bill Gates")
let book = Book(title: "Swift 入門到放棄", authors: [jobs,gates])
// 使用 \ 訪問key path 也適用于計算屬性
book[keyPath: \Book.title]
book[keyPath: \Book.primaryAuthor.name]
let authorKeyPath = \Book.primaryAuthor
type(of: authorKeyPath)
//如果編譯器可以推斷它拦键,你可以省略類型名
let nameKeyPath = authorKeyPath.appending(path: \.name)
book[keyPath: nameKeyPath]
//也可以通過下標(biāo)訪問
book[keyPath: \Book.authors[0].name]
定義KVO贬丛,以及deinit掉監(jiān)聽
import Foundation
class Child: NSObject {
let name:String
//設(shè)置KVO 必須用 @objc dynamic 修飾
@objc dynamic var age: Int
init(name: String,age: Int) {
self.name = name
self.age = age
super.init()
}
func celebrateBirthday() {
age += 1
}
}
let mia = Child(name: "mia", age: 5)
//設(shè)置KVO
let observation = mia.observe(\.age, options: [.initial,.old]) { (child, change) in
if let oldValue = change.oldValue {
print("\(child.name)'s age is from \(oldValue) to \(child.age)")
}else {
print("\(child.name)'s age is now \(child.age)")
}
}
mia.celebrateBirthday()
//deinit掉監(jiān)聽
observation.invalidate()
//這里不會觸發(fā)KVO
mia.celebrateBirthday()