Swift Equatable Protocol [英] Swift Equatable Protocol
问题描述
我正在为Swift提供本教程: https://www.raywenderlich.com/125311/make-game-like-candy-crush-spritekit-swift-part-1 并遇到此代码:
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
}
我写的确是这样,但Xcode是给出我的这些错误:
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
我从apple的文档中找到了这段代码: https://developer.apple.com/documentation/swift/equatable
I found this code from apple's documentation: https://developer.apple.com/documentation/swift/equatable
这和我写的很相似。怎么了?这对我来说似乎是个错误。我正在使用Xcode 6 Beta 2
Which is very similar to what I wrote. Whats wrong? This seems like a bug to me. I am using Xcode 6 Beta 2
这是我的整个Cookie类:
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
}
}
推荐答案
移动此功能
func == (lhs: Cookie, rhs: Cookie) -> Bool {
return lhs.column == rhs.column && lhs.row == rhs.row
}
在cookie类之外。这种方式很有意义,因为它在两个Cookie上使用时会覆盖全局范围内的==运算符。
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.
这篇关于Swift Equatable Protocol的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!