Isaiah
Isaiah

Reputation: 1902

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!

Upvotes: 6

Views: 2481

Answers (2)

Frankenstein
Frankenstein

Reputation: 16341

Conform Suit to String and combine them to create a unique identifier String.

struct Card: Identifiable {

    var id: String { "\(suit.rawValue)\(rank.rawValue)" }

    let suit: Suit
    let rank: Rank

    enum Suit: String {
        case spades, clubs, diamonds, hearts
    }
    enum Rank: Int {
        case one = 1, two, three, four, five, six, seven, jack, queen, king
    }
}

Caution: This can't be generalized for every scenario. Although this works fine in this particular one. Because we're using the concatenation of two strings together to compute the id of the Card's object.

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299355

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 }
}

Upvotes: 17

Related Questions