【发布时间】:2019-08-26 06:12:45
【问题描述】:
我正在尝试修复 RayWenderlich 网站上不再受支持的旧教程。 警告出现在三个文件中,Chain.swift、Cookie.swift 和 Swap.swift 来自“如何使用 SpriteKit 和 Swift 制作类似于 Candy Crush 的游戏:”教程
即使在浏览了许多地方出现的可用回复之后,我也不知所措。我正在努力理解这段代码在做什么,以便我可以修复它。我知道这只是一个警告,我可能会忽略它,但游戏也会在应该出现空白图块的地方显示 X,所以我怀疑它可能与此有关?
警告是这样的:
'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'Chain' to 'Hashable' by implementing 'hash(into:)' instead
文件示例
class Chain: Hashable, CustomStringConvertible {
var cookies: [Cookie] = []
var score = 0
enum ChainType: CustomStringConvertible {
case horizontal
case vertical
var description: String {
switch self {
case .horizontal: return "Horizontal"
case .vertical: return "Vertical"
}
}
}
var chainType: ChainType
init(chainType: ChainType) {
self.chainType = chainType
}
func add(cookie: Cookie) {
cookies.append(cookie)
}
func firstCookie() -> Cookie {
return cookies[0]
}
func lastCookie() -> Cookie {
return cookies[cookies.count - 1]
}
var length: Int {
return cookies.count
}
var description: String {
return "type:\(chainType) cookies:\(cookies)"
}
var hashValue: Int {
return cookies.reduce (0) { $0.hashValue ^ $1.hashValue }
}
static func ==(lhs: Chain, rhs: Chain) -> Bool {
return lhs.cookies == rhs.cookies
}
}
【问题讨论】:
-
我看到了。对不起,没有帮助。 Apple 文档更加晦涩难懂。
-
背景:
Hashable不再要求符合类型的hashValue: Int描述自己,而是要求他们接受Hasher,并将自己“混合”到其中(通过混合他们的领域)。以前人们很难为具有多个字段的对象导出良好的哈希值,通常会求助于 hack,例如对所有元素进行异或运算 (a ^ b ^ c),或者更糟糕的是,获取连接元素的字符串的字符串值 ("\(a)-\(b)-\(c)".hashValue)。现在,您只需告诉哈希器要哈希什么,它会使用适当的哈希算法代表您执行此操作。