Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Equatable Protocol

Tags:

ios

swift

xcode6

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     } } 
like image 719
Addison Avatar asked Jun 28 '14 14:06

Addison


People also ask

What is Equatable protocol Swift?

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.

Can a protocol conform to Equatable Swift?

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 .

What is Equatable and comparable in Swift?

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.

Is string Equatable Swift?

swift - Why "String?" does not conform to Equatable - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


1 Answers

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.

like image 156
Connor Avatar answered Sep 28 '22 19:09

Connor