Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Identifiable using two enum variables

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!

like image 971
Isaiah Avatar asked Dec 23 '22 17:12

Isaiah


1 Answers

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 }
}
like image 58
Rob Napier Avatar answered Jan 13 '23 15:01

Rob Napier