快速等值协议

我正在学习 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

我从苹果的文档中找到了这个代码: https://developer.apple.com/documentation/swift/equatable

和我写的很像。怎么了?我觉得这就是个错误。我正在使用 Xcode 6 Beta 2

编辑:

这就是我的饼干课:

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
}
}
25176 次浏览

Move this function

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

Outside of the cookie class. It makes sense this way since it's overriding the == operator at the global scope when it is used on two Cookies.

making the class an NSObject solved the equatable problems for me...

class Cookie: NSObject {
...
}

(got the tip from the iOS apprentice tutorials)

SWIFT 2:

As in swift 2 NSObject already conforms to Equatable.You don't need conformance at the top so it's like

class Cookie: NSObject {
...


}

And you need to override isEqual method as

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
}


}

This time isEqual method is inside the class. :)

EDIT for SWIFT 3: Change this method as

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


return lhs.column == rhs.column
}