![](/img/trans.png)
[英]Swift: "Type 'any Hashable' cannot conform to 'Hashable'"
[英]can swift functions and closures conform to Hashable?
假設我想要一Set
函數或閉包。 以下是我將如何去做:
typealias HandlerX = () -> ()
static var handlersX = Set<HandlerX>()
這會產生以下編譯器錯誤:
類型 'HandlerX' (aka '() -> ()') 不符合協議 'Hashable'
這是一個死胡同嗎?
是的,這是一條死胡同。 Hashable 並不是你的問題。 無法確定兩個閉包是否相等(這是 Hashable 的基本要求)。
您可以為關閉創建一個包裝器結構
struct Hashed<T>: Hashable {
let value: T
let hash: Int
init(value: T, hash: Int) {
self.value = value
self.hash = hash
}
public func hash(into hasher: inout Hasher) {
hasher.combine(hash)
}
static func == (lhs: Hashed<T>, rhs: Hashed<T>) -> Bool {
lhs.hashValue == rhs.hashValue
}
}
但是您需要了解閉包的身份。 例如,它可以是創建它的類,或者#filename + #line
,或者總是唯一的UUID()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.