代码之家  ›  专栏  ›  技术社区  ›  zardon

Swift:比较扑克牌-二进制比较不能应用

  •  0
  • zardon  · 技术社区  · 6 年前

    我在雨燕游乐场有以下代码 Card 结构已创建。

    我需要比较卡片,看看哪个值更高。

    理想情况下,我还需要检查所有形式的二进制操作 <, >, <=, >=, etc

    但是,我不断收到一个错误,上面写着:

    error: binary operator '>' cannot be applied to two 'Card' operands if (ace > king) {
        ~~~ ^ ~~~~
    

    另一条消息指出:

    注意:“>”的重载存在这些部分匹配的参数 列表:((),()),(UInt8,UInt8),(Int8,Int8),(UInt16,UInt16), (Int64,Int64),(UInt,UInt),(Int,Int),(UIContentSizeCategory, UIContentSizeCategory),(日期,日期),(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)), (ace>国王){

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

    我想知道我做错了什么。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Dávid Pásztor    6 年前

    你需要遵守法律 Comparable < >

    extension Card: Comparable {
        static func < (lhs: Card, rhs: Card) -> Bool {
            return lhs.rank.values.first < rhs.rank.values.first
        }
    }