【问题标题】:Swift set equatable sometimes true sometimes falseSwift set equatable 有时为真有时为假
【发布时间】:2020-03-09 03:33:15
【问题描述】:

我有一个符合 Hashable 的结构。这个模型放在Set。当我检查集合是否包含模型时,它会随机返回真/假。这是为什么呢?

enum Feature: String {
    case a
    case b
}

struct FeatureState: Hashable {
    let feature: Feature
    let isEnabled: Bool
}

extension FeatureState: Equatable {

    static func == (lhs: FeatureState, rhs: FeatureState) -> Bool {
        lhs.feature == rhs.feature
    }
}

let fs1 = FeatureState(feature: .a, isEnabled: false)
let fs2 = FeatureState(feature: .a, isEnabled: true)

featureStates.insert(fs1)
print(featureStates.contains(fs2)) // sometimes true, sometimes false

【问题讨论】:

    标签: swift set equality


    【解决方案1】:

    Set.contains 使用哈希来检查一个元素是否已经是Set 的一部分,并且仅当两个元素的哈希值相同时才使用== 运算符。因此,您需要提供自己的hash(into:) 实现,以使哈希值仅依赖于feature,而不依赖于isEnabled

    struct FeatureState {
        let feature: Feature
        let isEnabled: Bool
    }
    
    extension FeatureState: Hashable {
        static func == (lhs: FeatureState, rhs: FeatureState) -> Bool {
            lhs.feature == rhs.feature
        }
    
        func hash(into hasher: inout Hasher) {
            hasher.combine(feature)
        }
    }
    

    【讨论】:

    • 花几个小时试图找出遗留测试不再起作用的原因。非常感谢,我对此一无所知:o
    猜你喜欢
    • 1970-01-01
    • 2014-10-02
    • 2012-12-06
    • 2019-01-30
    • 1970-01-01
    • 2010-11-09
    • 2022-09-28
    • 2018-07-01
    • 1970-01-01
    相关资源
    最近更新 更多