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
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 } }
In Swift, an Equatable is a protocol that allows two objects to be compared using the == operator. The hashValue is used to compare two instances. To use the hashValue , we first have to conform (associate) the type (struct, class, etc) to Hashable property.
Overview. Types that conform to the Equatable protocol can be compared for equality using the equal-to operator ( == ) or inequality using the not-equal-to operator ( != ). Most basic types in the Swift standard library conform to Equatable .
In Swift, there's the Equatable protocol, which explicitly defines the semantics of equality and inequality in a manner entirely separate from the question of identity. There's also the Comparable protocol, which builds on Equatable to refine inequality semantics to creating an ordering of values.
swift - Why "String?" does not conform to Equatable - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With