gpt4 book ai didi

swift - 如何更新此 Hashable.hashValue 以符合新要求。?

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:35 27 4
gpt4 key购买 nike

我正在尝试修复 RayWenderlich 网站上不再受支持的旧教程。该警告出现在三个文件中,Chain.swift、Cookie.swift 和 Swap.swift,来自“如何使用 SpriteKit 和 Swift 制作类似 Candy Crush 的游戏:”教程

即使在探索了出现在许多地方的可用回复之后,我仍然不知所措。我正在努力理解这段代码在做什么,以便我可以修复它。我知道这只是一个警告,我可能可以忽略它,但游戏还在应该出现空白图 block 的地方显示 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
}
}

最佳答案

来自Hashable文档:

Hashing a value means feeding its essential components into a hash function, represented by the Hasher type. Essential components are those that contribute to the type’s implementation of Equatable. Two instances that are equal must feed the same values to Hasher in hash(into:), in the same order.

并且来自 hash(into:)文档:

The components used for hashing must be the same as the components compared in your type’s == operator implementation. Call hasher.combine(_:) with each of these components.

执行

static func ==(lhs: Chain, rhs: Chain) -> Bool {
return lhs.cookies == rhs.cookies
}

表明 cookies 是确定实例相等性的“基本组件”。因此

func hash(into hasher: inout Hasher) {
hasher.combine(cookies)
}

Hashable 要求的有效(合理)实现。

关于swift - 如何更新此 Hashable.hashValue 以符合新要求。?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55516776/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com