Skip to content

Instantly share code, notes, and snippets.

@vknabel
Created November 11, 2016 19:44
Show Gist options
  • Save vknabel/153c9bab1eb5e0d0c474a8b0a843ca48 to your computer and use it in GitHub Desktop.
Save vknabel/153c9bab1eb5e0d0c474a8b0a843ca48 to your computer and use it in GitHub Desktop.
Allows you to use any hash function in Sets/Dictionaries (Swift 3.0)
public extension AnyHashable {
public init(value: V, compare: @escaping (V, V) -> Bool, hash: @escaping (V) -> Int) {
self.init(CustomHashable(value: value, compare: compare, hash: hash))
}
}
public struct CustomHashable<V>: Hashable {
public let value: V
public let compare: (V, V) -> Bool
public let hash: (V) -> Int
public init(value: V, compare: @escaping (V, V) -> Bool, hash: @escaping (V) -> Int) {
self.value = value
self.compare = compare
self.hash = hash
}
public static func with(compare: @escaping (V, V) -> Bool, hash: @escaping (V) -> Int) -> (V) -> CustomHashable<V> {
return {
CustomHashable(value: $0, compare: compare, hash: hash)
}
}
public static func == (lhs: CustomHashable, rhs: CustomHashable) -> Bool {
return lhs.compare(lhs.value, rhs.value) && rhs.compare(lhs.value, rhs.value)
}
public var hashValue: Int {
return hash(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment