Created
November 11, 2016 19:44
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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