Har*_*ern 2 xcode hashable swift
我正在尝试修复 RayWenderlich 网站上的旧教程,不再受支持。警告出现在三个文件中,Chain.swift、Cookie.swift 和 Swap.swift 来自“如何使用 SpriteKit 和 Swift 制作像糖果粉碎一样的游戏:”教程
即使在探索了出现在许多地方的可用回复后,我仍然不知所措。我正在努力理解这段代码在做什么,以便我可以修复它。我知道这只是一个警告,我可能可以忽略它,但游戏还显示 X 应该出现空白图块的位置,所以我怀疑它可能与此有关?
警告是这样的:
'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'Chain' to 'Hashable' by implementing 'hash(into:)' instead
Run Code Online (Sandbox Code Playgroud)
文件示例
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
}
}
Run Code Online (Sandbox Code Playgroud)
来自Hashable文档:
散列一个值意味着将其基本组成部分提供给一个散列函数,由 Hasher 类型表示。基本组件是那些有助于 Equatable 类型实现的组件。两个相等的实例必须以相同的顺序将相同的值以 hash(into:) 形式提供给 Hasher。
从hash(into:)文档中:
用于散列的组件必须与您的类型的 == 运算符实现中比较的组件相同。使用这些组件中的每一个调用 hasher.combine(_:) 。
实施
static func ==(lhs: Chain, rhs: Chain) -> Bool {
return lhs.cookies == rhs.cookies
}
Run Code Online (Sandbox Code Playgroud)
表明这cookies是确定实例相等性的“基本组件”。所以
func hash(into hasher: inout Hasher) {
hasher.combine(cookies)
}
Run Code Online (Sandbox Code Playgroud)
是需求的有效(和合理)实现Hashable。
| 归档时间: |
|
| 查看次数: |
1777 次 |
| 最近记录: |