Swift Struct作为Dictionary Key不使用自定义hashinto :)函数

问题描述

由于某种原因,如果您拥有具有自定义Equatable一致性的结构的属性,则似乎无法将结构化为Hashable但使用认的Equatable一致性。

例如:

struct Test: Hashable {

    let value: Double
    let testEnum: TestEnum
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(value)
    }
}

enum TestEnum {
    case one(value: String)
    case two(value: String)
}

extension TestEnum: Equatable {
    static func ==(lhs: TestEnum,rhs: TestEnum) -> Bool {
        switch (lhs,rhs) {
        
        case (.one(let lhsType),.one(let rhsType)):
            return lhsType == rhsType
        case (.two(let lhsType),.two(let rhsType)):
            return lhsType == rhsType
        default:
            return false
        }
    }
}

var testDictionary:[Test: Int] = [Test: Int]()


let test = Test(value: 22,testEnum: .one(value: "one"))
let newTest = Test(value: 22,testEnum: .two(value: "two"))

testDictionary[test] = 23
print(testDictionary[test]!) //this prints 23
testDictionary[newTest] = 22
print(testDictionary[test]!) //this prints 23 as well
print(test.hashValue) // same hashvalue
print(newTest.hashValue) // same hashvalue

我假设由于仅在hash(into :)函数中使用了value属性,因此它将忽略testEnum。哈希值相同,但是字典将它们视为两个不同的键。

有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)