Swift Equatable Protocol

Addison picture Addison · Jun 28, 2014 · Viewed 24.6k times · Source

I was folling this tutorial for Swift: https://www.raywenderlich.com/125311/make-game-like-candy-crush-spritekit-swift-part-1 and came across this code:

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

I wrote exactly that, but Xcode is giving my these errors:

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

I found this code from apple's documentation: https://developer.apple.com/documentation/swift/equatable

Which is very similar to what I wrote. Whats wrong? This seems like a bug to me. I am using Xcode 6 Beta 2

EDIT:

This is my whole Cookie class:

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

Answer

Connor picture Connor · Jun 28, 2014

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.