Skip to content

Instantly share code, notes, and snippets.

@zats
Created July 8, 2019 18:10
Show Gist options
  • Save zats/866384a7f3ec81c7049b763c25762302 to your computer and use it in GitHub Desktop.
Save zats/866384a7f3ec81c7049b763c25762302 to your computer and use it in GitHub Desktop.
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)
}
}
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