Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Creating a hashable tuple-like struct

Tags:

generics

swift

I'm trying to create a hashable tuple-like object which can hold any type of object for use as a key in a dictionary. I use the structure in two places, once to hold 2 Ints, and once to hold a double and the previously mentioned 2 Int struct.

My current implementation cheats a little bit. I created a struct Suple which holds two ints, and is hashable, and then another struct Duple which holds a double and a suple, and is hashable. This works, but I figure 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 practically identical to Anton's EXCEPT for the after the == in the declaration of equality. I didn't realize this was needed, and after adding that, it now works!

like image 947
KHAAAAAAAAN Avatar asked Aug 27 '26 06:08

KHAAAAAAAAN


1 Answers

Something like this?

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
like image 111
0x416e746f6e Avatar answered Aug 30 '26 21:08

0x416e746f6e



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!