You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取包含遵循Equatable与Hashable的Survey结构体的数组哈希值?

获取包含Survey结构体的数组的哈希值

要解决这个问题,核心是先让你的Survey结构体正确遵循Hashable协议——因为只有当数组的元素类型实现了Hashable,数组本身才能计算哈希值。我们一步步来调整你的代码:

1. 补全Equatable实现并添加Hashable支持

你的现有代码里Equatable的==方法没写完,而且还没实现Hashable。先把这部分补全:

方式一:利用Swift自动合成协议实现(Swift 5.1+推荐)

从Swift 5.1开始,只要结构体的所有存储属性都遵循Equatable和Hashable,编译器会自动为你生成Equatable和Hashable的实现代码,不用手动写:

import Foundation

public struct Survey: Equatable, Hashable { // 直接声明遵循两个协议
    public let id: String
    public let createdAt: Date
    public let updatedAt: Date
    public let title: String
    public let type: String
}

注:String和Date本身都遵循Hashable,所以这个自动合成是完全有效的。

方式二:手动实现Hashable(兼容旧版本Swift)

如果你需要支持Swift 5.1之前的版本,或者需要自定义哈希逻辑,可以手动实现Hashable的hash(into:)方法,同时补全Equatable的==方法:

import Foundation

public struct Survey {
    public let id: String
    public let createdAt: Date
    public let updatedAt: Date
    public let title: String
    public let type: String
}

extension Survey: Equatable {
    public static func ==(lhs: Survey, rhs: Survey) -> Bool {
        // 补全完整的相等判断逻辑
        return lhs.id == rhs.id
            && lhs.createdAt == rhs.createdAt
            && lhs.updatedAt == rhs.updatedAt
            && lhs.title == rhs.title
            && lhs.type == rhs.type
    }
}

extension Survey: Hashable {
    public func hash(into hasher: inout Hasher) {
        // 将所有参与相等判断的属性都传入hasher,保证相等的实例哈希值相同
        hasher.combine(id)
        hasher.combine(createdAt)
        hasher.combine(updatedAt)
        hasher.combine(title)
        hasher.combine(type)
    }
}

2. 获取数组的哈希值

当Survey正确实现Hashable后,[Survey]类型会自动获得Hashable的支持(因为Swift的Array在元素为Hashable时,本身就遵循Hashable)。你可以直接通过hashValue属性(Swift 5.0及之前)或者使用hash(into:)方法来获取哈希值:

// 示例用法
let survey1 = Survey(id: "1", createdAt: Date(), updatedAt: Date(), title: "Survey 1", type: "Type A")
let survey2 = Survey(id: "2", createdAt: Date(), updatedAt: Date(), title: "Survey 2", type: "Type B")
let surveyArray = [survey1, survey2]

// 获取哈希值
let arrayHashValue = surveyArray.hashValue
print("数组哈希值:\(arrayHashValue)")

// 或者用Swift 5.0+的hash(into:)方法自定义哈希组合
var hasher = Hasher()
surveyArray.hash(into: &hasher)
let customArrayHash = hasher.finalize()
print("自定义数组哈希值:\(customArrayHash)")

关键注意点

  • 哈希值的一致性:确保hash(into:)方法中包含所有参与==判断的属性,这样相等的实例一定会有相同的哈希值(反过来哈希值相同不一定实例相等,这是哈希的正常特性)。
  • 不要依赖哈希值的稳定性:哈希值可能会在不同的程序运行、不同Swift版本甚至不同设备上变化,所以不要把哈希值用作持久化存储的标识。

内容的提问来源于stack exchange,提问作者Isuru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:04:46