Swift4 - KVC与KVO

KVC和KVO是我们开发中常用的功能,现在来看一下在Swift4中的变化

KVC

在Swift4的时候,Struct也支持KVC,我们不在使用setValue: forKeypath的方式,而是使用新的语法特性,下面看一下例子,参考这里

struct Person {
    var name: String
}

struct Book {
    var title: String
    var authors: [Person]
    var primaryAuthor: Person {
        return authors.first!
    }
}

let abelson = Person(name: "Haeold Abelson")
let sussman = Person(name: "Garald Jay Sussman")
var book = Book(title: "tructure and Interpretation of Computer Programs", authors: [abelson, sussman])

//get
//1 keyPath以\开始,然后开始组合结构体和属性
let title = book[keyPath: \Book.title]
print(title) //tructure and Interpretation of Computer Programs

//2 keypath可以进入多层深入搜索查找,也可以对计算属性进行操作
let name = book[keyPath: \Book.primaryAuthor.name]
print(name) //Haeold Abelson

//set
book[keyPath: \Book.title] = "KVC"
print(book[keyPath: \Book.title]) // KVC

对象的路径操作

//先获取一个路径
let authorKeyPath = \Book.primaryAuthor
//拼接子路径
let nameKeyPath = authorKeyPath.appending(path: \.name)
let newName = book[keyPath: nameKeyPath]
print(newName) //Haeold Abelson

KVO

@objcMembers class Food: NSObject {
    dynamic var string: String
    override init() {
        string = "hotdog"
        super.init()
    }
}

let food = Food()
let observation = food.observe(\.string) { (foo, changed) in
     print("new food string: \(foo.string)")
}
food.string = "not hotdog" // new food string: not hotdog
上面代码很简单,创建了一个Food类,拥有一个string属性,但是需要注意几件事情:

1)用KVO依然需要是NSObject类或子类,Swift4中swift类不再自动被推测为继承于NSObject,所以当我们在编写swift的代码时,需要为类添

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值