2

有什么方法可以参考selfSwift 4 的 new KeyPaths?

像这样工作正常,我们可以解决一个对象的属性:

func report(array: [Any], keyPath: AnyKeyPath) {
    print(array.map({ $0[keyPath: keyPath] }))
}

struct Wrapper {
    let name: String
}

let wrappers = [Wrapper(name: "one"), Wrapper(name: "two")]
report(array: wrappers, keyPath: \Wrapper.name)

但对我来说,解决一个对象本身似乎是不可能的:

let strings = ["string-one", "string-two"]
report(array: strings, keyPath: \String.self) // would not compile

我想应该有一些明显的方法吗?

编辑:

或者简单地说:

let s = "text-value"
print(s[keyPath: \String.description]) // works fine
print(s[keyPath: \String.self]) // does not compile
4

3 回答 3

3

不幸的是,这不是 Swift 键路径当前支持的东西。但是,我确实认为这是他们应该支持的(使用您尝试使用的确切语法,例如\String.self)。所有表达式都有一个隐式.self成员,它只计算表达式,所以它似乎是一个非常自然的扩展,允许.self在 keypaths 中(编辑:这是现在正在宣传的东西)。

在支持之前(如果有的话),您可以使用协议扩展来破解它,该扩展添加了一个仅转发到的计算属性self

protocol KeyPathSelfProtocol {}
extension KeyPathSelfProtocol {
  var keyPathSelf: Self {
    get { return self }
    set { self = newValue }
  }
}

extension String : KeyPathSelfProtocol {}

let s = "text-value"
print(s[keyPath: \String.description])
print(s[keyPath: \String.keyPathSelf])

您只需要将要使用“self keypaths”的类型与 to 保持一致KeyPathSelfProtocol

于 2018-03-11T21:18:24.127 回答
2

是的,有一种引用方式,self但它在 Swift 4 中不可用。它是在 2018 年 9 月为 Swift 5 实现的,它被称为Identity key path

你按照你的建议使用它

let s = "text-value"
print(s[keyPath: \String.self]) // works in Swift 5.0

即使 Swift 5 尚未发布,您也可以通过下载开发版本来试用它:https ://swift.org/download/#releases

于 2019-01-24T15:59:15.410 回答
0

的行为keyPath与Key-Value Coding 类似:通过订阅获取类/结构的成员的值key

在 Swiftself中不是类的成员,description是。

你会期待什么结果

report(array: wrappers, keyPath: \Wrapper.self)
于 2018-03-11T20:00:37.573 回答