Skip to content

Instantly share code, notes, and snippets.

@ddunbar
Created August 14, 2016 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddunbar/a06e8c6c6dadb0432dec1f744d7f036f to your computer and use it in GitHub Desktop.
Save ddunbar/a06e8c6c6dadb0432dec1f744d7f036f to your computer and use it in GitHub Desktop.
HashableBox
/// Box for exposing an item as a hashable.
public struct HashableBox<T, H: Hashable>: Hashable {
/// The wrapped item.
public let item: T
private let accessor: (T) -> H
/// Create a new hashable box for `item` where `accessor` defines the hashable content.
public init(_ item: T, accessor: @escaping (T) -> H) {
self.item = item
self.accessor = accessor
}
fileprivate var hashableItem: H {
return accessor(item)
}
public var hashValue: Int {
return hashableItem.hashValue
}
}
public func ==<T, H: Hashable>(lhs: HashableBox<T, H>, rhs: HashableBox<T, H>) -> Bool {
return lhs.hashableItem == rhs.hashableItem
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment