使用KeyPath实现Swift的KVC和KVO

2018-04-11  本文已影响84人  狂奔的胖蜗牛

KeyPath

KeyPath的语法为\Type.property.property.....

let nameCountAccessor = \Animal.name.count

现在可以使用KeyPath以一种新的姿势实现KVC和KVO了。

KVC

class Persion {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}
let one = Persion(name: "AB", age: 10)
let path = \Persion.name
//设置name的值
one[keyPath: path] = "CD"
print(one[keyPath: path])//CD

Swift4中,可以对结构体进行KVC操作。

struct ValueType {
    var name: String
}

var obj = ValueType(name: "yu")
let name = \ValueType.name
//set kvc
obj[keyPath: name] = "hua"
//get
print(obj[keyPath: name])//hua

KVO

@objcMembers class Student: NSObject {
    dynamic var name: String
    init(name: String) {
        self.name = name
    }
}
let stu = Student(name: "a")
let ob: NSKeyValueObservation! = stu.observe(\.name) { (ob, changed) in
    print(ob.name)//aaa
}
stu.name = "aaa"

注意点:

上一篇 下一篇

猜你喜欢

热点阅读