Swift Equatable Protocol

时间:2014-06-28 14:47:55

标签: ios swift xcode6

我正在使用Swift的这个教程:https://www.raywenderlich.com/125311/make-game-like-candy-crush-spritekit-swift-part-1并遇到了这段代码:

func == (lhs: Cookie, rhs: Cookie) -> Bool {
    return lhs.column == rhs.column && lhs.row == rhs.row
}

我写的确是这样,但Xcode给出了我的这些错误:

Consecutive declarations on a line must be separated by ';'
Expected declaration operators are only allowed at global scope

我在Apple的文档中找到了这段代码:https://developer.apple.com/documentation/swift/equatable

这与我写的非常相似。怎么了?这对我来说似乎是个错误。我正在使用Xcode 6 Beta 2

编辑:

这是我的整个Cookie类:

class Cookie: Printable, Hashable {
    var column: Int
    var row: Int
    let cookieType: CookieType
    let sprite: SKSpriteNode?

    init(column: Int, row: Int, cookieType: CookieType) {
        self.column = column
        self.row = row
        self.cookieType = cookieType
    }

    var description: String {
        return "type:\(cookieType) square:(\(column),\(row))"
    }

    var hashValue: Int {
        return row * 10 + column
    }

    func ==(lhs: Cookie, rhs: Cookie) -> Bool {
        return lhs.column == rhs.column && lhs.row == rhs.row
    }
}

3 个答案:

答案 0 :(得分:145)

移动此功能

func == (lhs: Cookie, rhs: Cookie) -> Bool {
    return lhs.column == rhs.column && lhs.row == rhs.row
}

在cookie类之外。这是有道理的,因为当它在两个Cookie上使用时,它会覆盖全局范围内的==运算符。

答案 1 :(得分:32)

SWIFT 2:

正如在swift 2中NSObject已经符合Equatable。你不需要在顶部达到一致性,所以它就像

一样
class Cookie: NSObject {
    ...

}

您需要将isEqual方法覆盖为

class Cookie:NSObject{
    var column: Int
    var row: Int

    //..........

    override func isEqual(object: AnyObject?) -> Bool {
        guard let rhs = object as? Cookie else {
            return false
        }
        let lhs = self

        return lhs.column == rhs.column
    }

}

这次isEqual方法在类中。 :)

EDIFT for SWIFT 3:将此方法更改为

override func isEqual(_ object: AnyObject?) -> Bool {
        guard let rhs = object as? Cookie else {
            return false
        }
        let lhs = self

        return lhs.column == rhs.column
    }

答案 2 :(得分:6)

使该类成为NSObject为我解决了相同的问题...

class Cookie: NSObject {
...
}

(从iOS学徒教程获得提示)