![](/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.