KeyPath - ShenYj/ShenYj.github.io GitHub Wiki

KeyPath

Swift 5.1重新学习到使用已经很久了,KeyPath 的使用场景最常见的就是在使用高阶函数 sort 函数时会用到,这个预发时长会遗忘,比如是\还是/,所以还是整理下笔记,方便后续查阅

什么是 KeyPath

  • 不需要实例就能表示属性位置&类型
  • 解释在一个文件中,哪个位置有什么类型的东西

KeyPath 组成

KeyPath<类型名称,String>

\ + 类型名称 + . + 属性名称

KeyPath 使用

  • 用下表存取:object[keyPath: path]
let cat = Cat(name: "蛋蛋")
/// 类型名称可以省略
cat.name = cat[keyPath: \.name]
cat.name = cat[keyPath: \Cat.name]

/// 完整写法
let keyPath: KeyPath<Cat, String> = \Cat.name

/// 将 KeyPath转成clourse
let Clourse: (Cat) -> String = \.name
  • 可转换成clourse: (Root) -> Value
let cats = [Cat(name: "蛋蛋"), Cat(name: "秘密")]

/// 被自动转换成 clourse
print(cats.map(\.name))
  • 都是Hashable的

补充

除了 KeyPath类型外,还有

  • WritableKeyPath
  • ReferenceWritableKeyPath
  • PartialKeyPath
  • AnyKeyPath

⚠️ **GitHub.com Fallback** ⚠️