ios - Swift Equatable P

我正在为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
    }
}
Addison asked 2019-09-10T09:46:51Z
3个解决方案
145 votes

移动此功能

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

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

Connor answered 2019-09-10T09:47:11Z
32 votes

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方法在类里面。:)

编辑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
    }
LC 웃 answered 2019-09-10T09:48:02Z
6 votes

让这个类成为NSObject为我解决了相同的问题......

class Cookie: NSObject {
...
}

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

Felipe Ignacio Noriega Alcaraz answered 2019-09-10T09:48:32Z
translate from https://stackoverflow.com:/questions/24467960/swift-equatable-protocol