I have the following code in Swift playground where a Card
struct is created.
I need to compare cards to see what value is higher.
Ideally, I also need to check against all forms of binary operations <, >, <=, >=, etc
However, I keep getting an error that says:
error: binary operator '>' cannot be applied to two 'Card' operands if (ace > king) {
~~~ ^ ~~~~
A further message states:
note: overloads for '>' exist with these partially matching parameter lists: ((), ()), (UInt8, UInt8), (Int8, Int8), (UInt16, UInt16), (Int16, Int16), (UInt32, UInt32), (Int32, Int32), (UInt64, UInt64), (Int64, Int64), (UInt, UInt), (Int, Int), (UIContentSizeCategory, UIContentSizeCategory), (Date, Date), (IndexPath, IndexPath), (IndexSet.Index, IndexSet.Index), ((A, B), (A, B)), ((A, B, C), (A, B, C)), ((A, B, C, D), (A, B, C, D)), ((A, B, C, D, E), (A, B, C, D, E)), ((A, B, C, D, E, F), (A, B, C, D, E, F)), (Self, Other), (Self, R) if (ace > king) {
struct Card : Equatable {
// nested Suit enumeration
enum Suit: Character {
case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣"
}
// nested Rank enumeration
enum Rank: Int {
case two = 2, three, four, five, six, seven, eight, nine, ten
case jack, queen, king, ace
struct Values {
let first: Int, second: Int?
}
var values: Values {
switch self {
case .ace:
return Values(first: 11, second: nil)
case .jack, .queen, .king:
return Values(first: 10, second: nil)
default:
return Values(first: self.rawValue, second: nil)
}
}
}
// Card properties and methods
let rank: Rank, suit: Suit
var description: String {
var output = "suit is \(suit.rawValue),"
output += " value is \(rank.values.first)"
if let second = rank.values.second {
output += " or \(second)"
}
return output
}
}
extension Card {
public static func == (lhs: Card, rhs: Card) -> Bool {
return ((lhs.rank == rhs.rank) && (lhs.suit == rhs.suit))
}
}
// Try to compare two cards
let ace = Card(rank: .ace, suit: .clubs)
let king = Card(rank: .king, suit: .diamonds)
if (ace > king) {
print ("Ace is higher value")
}
else {
print ("Ace is NOT higher")
}
I am wondering what I am getting wrong.
You need to conform to the Comparable
protocol to be able to use the comparison operators (<
and >
).
extension Card: Comparable {
static func < (lhs: Card, rhs: Card) -> Bool {
return lhs.rank.values.first < rhs.rank.values.first
}
}