当前位置:  开发笔记 > IOS > 正文

错误:不符合协议“ Equatable”

如何解决《错误:不符合协议“Equatable”》经验,为你挑选了1个好方法。

我是新手,并且正在阅读教程以了解更多信息。

在以下代码中,我定义了自定义运算符(<和==),但是代码工作正常,但是Xcode在代码的第一行显示了这些错误。

Type 'SuitedCard' does not conform to protocol 'Equatable'
Type 'SuitedCard' does not conform to protocol 'Comparable'

这是代码:

struct SuitedCard: Equatable, Comparable {

    // a card can be ??, ??, ??, ??
    enum Suit {
        case hearts
        case spades
        case diamonds
        case clubs
    }

    // the possible values of a card
    enum Value: Int {
        case two = 2
        case three = 3
        case four = 4
        case five = 5
        case six = 6
        case seven = 7
        case eight = 8
        case nine = 9
        case ten = 10
        case jack = 11
        case queen = 12
        case king = 13
        case ace = 14
    }

    // properties
    let suit: Suit
    let value: Value
    var isFaceDown: Bool
}

var valueArray: [SuitedCard.Value] = [.ten, .jack, .queen, .king]


func ==(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    for cardValue in valueArray {
        if lhs.value == cardValue {
            for cardValue2 in valueArray {
                if rhs.value == cardValue2 {
                    return true
                }
            }
        }
    }
    if lhs.value == rhs.value {
        return true
    }
    return false
}

func <(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    var lhsRawValue: Int
    var rhsRawValue: Int
    if lhs.value == .jack || lhs.value == .queen || lhs.value == .king {
        lhsRawValue = 10
    } else {
        lhsRawValue = lhs.value.rawValue
    }
    if rhs.value == .jack || rhs.value == .queen || rhs.value == .king {
        rhsRawValue = 10
    } else {
        rhsRawValue = rhs.value.rawValue
    }
    return lhsRawValue < rhsRawValue
}

let smaller = SuitedCard(suit: .hearts, value: .five, isFaceDown: true)

let bigger = SuitedCard(suit: .diamonds, value: .six, isFaceDown: false)

smaller >= smaller

smaller < bigger

怎么了?



1> OOPer..:

在Swift 3中,协议所需的运算符被声明为静态成员。

使用此类协议的一种方法是将操作员定义作为静态成员移入结构:

struct SuitedCard: Comparable { //### Comparable implies Equatable

    //...

    // function for custom operator ==
    static func ==(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
        //...
        return false
    }
    // function for custom operator <
    static func <(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
        //...
        return false
    }
}

另一种方法,您可以使用扩展名声明对协议的符合性:

struct SuitedCard {

    //...
}

// function for custom operator ==
func ==(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    //...
    return false
}
// function for custom operator <
func <(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    //...
    return false
}

extension SuitedCard: Comparable {}

推荐阅读
小白也坚强_177
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有