Home > Software design >  How to compare two different types for equality
How to compare two different types for equality

Time:12-12

I have a protocol called Card.

protocol Card: Hashable, Identifiable, Comparable, CustomStringConvertible {
    var rank: Rank { get }
    var suit: Suit { get }
}

extension Card {
    
    var id: Int {
        hashValue
    }
    
    static func <(lhs: Self, rhs: Self) -> Bool {
        lhs.rank < rhs.rank
    }
    
    var description: String {
        switch suit {
        case .spades: return SpadeCard(rank: rank).description
        case .hearts: return HeartCard(rank: rank).description
        case .diamonds: return DiamondCard(rank: rank).description
        case .clubs: return ClubCard(rank: rank).description
        }
    }
}

I want several types to conform to this. One of which is called SpadeCard.

struct SpadeCard: Card {
    
    public let rank: Rank
    public let suit: Suit = .spades
    
    public var description: String {
        return            
  • Related