Suppose I want to have a Set
of functions or closures. Here's how I would go about it:
typealias HandlerX = () -> ()
static var handlersX = Set<HandlerX>()
This produces the following compiler error:
Type 'HandlerX' (aka '() -> ()') does not conform to protocol 'Hashable'
Is this a dead end?
Yes, this is a dead end. Hashable isn't really your problem; there's no way to decide whether two closures are Equal (which is a base requirement of Hashable).
You can create a wrapper struct for closure
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
}
}
But you need to understand the identity of your closures. For example, it can be the class that created it, or #filename + #line
, or always unique with UUID()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.