Swift编程

Swift 5 新特性系列之二 Identity key pat

2019-04-20  本文已影响1人  豆志昂扬

在理解身份特征路径(Identity key path)之前,必须要对key path有清晰的认识,如key path的基本定义,ReferenceWritableKeyPath和WritableKeyPath的关系,如何把两个key path结合起来使用等。如有疑惑可以参看这里

Identity key path - 身份特征路径?

提案出处:

https://github.com/apple/swift-evolution/blob/master/proposals/0227-identity-keypath.md

细节

在Swift中每个值都有一个特别的属性.self, 我们使用它来获取整个值。
从兼容Cocoa KVC考虑的话,身份特征路径(Identity key path)对应这 @“self”。

var value = \Int.self
var height = 1
print(height[keyPath: value]) // 1
height[keyPath: value] = 5
print(height[keyPath: value]) // 5

以此类推,我们可以通过 .self 来访问 self 本身。

let id = \Int.self

x[keyPath: id] = 3
print(x[keyPath: id]) // 输出3

struct Employee {
  var name: String
  var position: String
}

func updateValue(of vc: ValueController<Employee>) {
  vc[\.self] = Employee(name: "Cassius Green", position: "Power Caller")
}

身份特征路径(identity key path) 其实是一个WritableKeyPath<T, T>, 因为它可以用来修改可变值,但其不能修改不可变的引用。

更多

获取更多内容请关注微信公众号豆志昂扬:

上一篇 下一篇

猜你喜欢

热点阅读