Using Swift 5.3, how can I implement the Identifiable protocol on a struct by having its identity depend on the combination of two enum variables?
The code in question is simple,
struct Card: Identifiable {
    let suit: Suit
    let rank: Rank
    
    enum Suit {
        case spades, clubs, diamonds, hearts
    }
    
    enum Rank: Int {
        case one = 1, two, three, four, five, six, seven, jack, queen, king
    }
}
The above struct does not conform to the Identifiable protocol yet. How can I implement its identity as being the unique combination of its suit and rank (which are only created once)? Essentially, its identity could be 'spades-1' or 'diamonds-jack'. Furthermore, if possible I would like to retain the rank as an Int type, to allow for arithmetic later. Thank you in advance!
Since this type is exactly defined by the combination of its values, it is its own Identifier. So as long as Card is Hashable, it can identify itself:
extension Card: Hashable, Identifiable {
    var id: Self { self }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With