-
-
Save zats/866384a7f3ec81c7049b763c25762302 to your computer and use it in GitHub Desktop.
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<T>: Hashable { | |
public let value: T | |
public typealias HashCalculator = (T, inout Hasher) -> Void | |
public typealias EqualityCalculator = (T, T) -> Bool | |
private let hashCalculator: HashCalculator | |
private let equalityCalculator: EqualityCalculator | |
public init(value: T, hashCalculator: @escaping HashCalculator, equalityCalculator: @escaping EqualityCalculator) { | |
self.value = value | |
self.hashCalculator = hashCalculator | |
self.equalityCalculator = equalityCalculator | |
} | |
public static func == (lhs: CustomHashable<T>, rhs: CustomHashable<T>) -> Bool { | |
return lhs.equalityCalculator(lhs.value, rhs.value) | |
} | |
public func hash(into hasher: inout Hasher) { | |
hashCalculator(self.value, &hasher) | |
} | |
} |
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
private func pointHashCalculator(point: CGPoint, hasher: inout Hasher) { | |
hasher.combine(Int(point.x)) | |
hasher.combine(Int(point.y)) | |
} | |
private func pointEqualityCalculator(p1: CGPoint, p2: CGPoint) -> Bool { | |
return Int(p1.x) == Int(p2.x) && Int(p1.y) == Int(p2.y) | |
} | |
func hashTheUnhashable() { | |
var points: Set<CustomHashable<CGPoint>> = [] | |
for p in allPoints { | |
points.insert(CustomHashable(value: p, | |
hashCalculator: pointHashCalculator, | |
equalityCalculator: pointEqualityCalculator)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment