Swift - creating a hashable tuple structure
I am trying to create a hashable tuple-like object that can contain any type of object to use as a key in a dictionary. I use the structure in two places, once to hold 2 Ints, and once to hold the double and previously mentioned 2 Int structure.
My current version is cheating a little. I created a struct Suple
that contains two ints and hashable, and then another struct Duple
that contains double and suple and is hashable. This works, but I believe there must be a better, cleaner way to implement this. After searching and messing around with generics, I can't seem to get it to work, so any advice would be appreciated.
EDIT: My code actually looks almost identical to Anton EXCEPT for after ==
in the equality declaration. I didn’t understand that this is necessary, and adding it now works!
source to share
Something like that?
struct Duplet<A: Hashable, B: Hashable>: Hashable {
let one: A
let two: B
var hashValue: Int {
return one.hashValue ^ two.hashValue
}
init(_ one: A, _ two: B) {
self.one = one
self.two = two
}
}
func ==<A, B> (lhs: Duplet<A, B>, rhs: Duplet<A, B>) -> Bool {
return lhs.one == rhs.one && lhs.two == rhs.two
}
let a = Duplet<Int, Int>(4, 2)
a.one
a.two
a.hashValue
let b = Duplet<Double, Double>(1.0, 2.0)
b.one
b.two
b.hashValue
let c = Duplet<Int, Double>(4, 5.0)
c.one
c.two
c.hashValue
source to share