generics - Swift - Creating a hashable tuple-like struct -
i'm trying create hashable tuple-like object can hold type of object use key in dictionary. use structure in 2 places, once hold 2 ints, , once hold double , mentioned 2 int struct.
my current implementation cheats little bit. created struct suple
holds 2 ints, , hashable, , struct duple
holds double , suple, , hashable. works, figure there must better, cleaner way implement this. after searching , messing around generics can't seem work, advice appreciated.
edit: code looks practically identical anton's except after ==
in declaration of equality. didn't realize needed, , after adding that, works!
something this?
struct duplet<a: hashable, b: hashable>: hashable { let one: let two: b var hashvalue: int { return one.hashvalue ^ two.hashvalue } init(_ one: a, _ two: b) { self.one = 1 self.two = 2 } } func ==<a, b> (lhs: duplet<a, b>, rhs: duplet<a, b>) -> bool { return lhs.one == rhs.one && lhs.two == rhs.two } let = 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
Comments
Post a Comment