Swift集可等于有时为true有时为false

问题描述 投票:0回答:1

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

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个回答
0
投票

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.