![](/img/trans.png)
[英]Why can’t you use a generic Self reference in a Swift 3.2/4 KeyPath typealias?
[英]Reference to self with Swift 4's KeyPath
Swift 4的新KeyPath
是否可以引用self
?
这样的事情可以正常工作,我们可以解决对象的属性:
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
不幸的是,这不是Swift关键路径当前支持的东西。 但是,我确实认为这是他们应该支持的东西(使用您尝试使用的确切语法,例如\\String.self
)。 所有表达式都有一个隐式的.self
成员,该成员仅对该表达式求值,因此在键.self
中允许.self
似乎是一个很自然的扩展( 编辑:这是现在正在推广的东西 )。
在受支持之前(如果有的话),您可以使用协议扩展来对其进行破解,该协议扩展会添加一个仅转发给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])
您只需要将要使用“自身密钥路径”的类型与KeyPathSelfProtocol
进行KeyPathSelfProtocol
。
是的,有一种引用self
的方法,但是在Swift 4中不可用。它是在2018年9月为Swift 5实现的,称为身份密钥路径 。
您可以像建议的那样使用它
let s = "text-value"
print(s[keyPath: \String.self]) // works in Swift 5.0
即使Swift 5尚未发布,您也可以通过以下网址下载开发版本进行试用: https : //swift.org/download/#releases
的行为keyPath
相同
相似的键-值编码:过得去的类/结构的成员的值key
订阅。
在Swift中self
不是类的成员, description
是。
您希望得到什么结果
report(array: wrappers, keyPath: \Wrapper.self)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.