在“Equatable”上引用运算符函数“==”要求“Dictionary<U, V?>.Values”符合“Equatable”

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

我有一个定义字典的类:

class InventoryDictionary <U : Hashable, V> : Equatable {

    var dictionary : [ U : V? ]  = [:]

    static func ==(lhs: InventoryDictionary, rhs: InventoryDictionary) -> Bool {
       return    lhs.dictionary.keys == rhs.dictionary.keys
              && lhs.dictionary.values == rhs.dictionary.values
    }
}

XCode 显示错误:

在“Equatable”上引用运算符函数“==”要求“Dictionary.Values”符合“Equatable”

我正在尝试使 InventoryDictionary 符合

Equatable
Swift 协议。

==
重载函数中,可以比较
dictionary.keys
是否相等,但不能比较值(这是可以理解的)。

但是我不清楚如果我不编写代码来检查每个

V
(值)或者是否有某种方法可以使 Swift-generic
V
等价,那么我是否可以解决这个问题。

解决这个问题的好方法是什么?

swift dictionary swift-protocols equatable
2个回答
2
投票

首先,

V
也必须是
Equatable
。也就是说,声明应该是

class InventoryDictionary<U: Hashable, V: Equatable> : Equatable {

但是,您不应该使用

class
。最好你应该为这个用例使用
struct
,因为这样将为你生成公平性。

struct InventoryDictionary<U: Hashable, V: Equatable> : Equatable {
    var dictionary: [U: V] = [:]
}

如果你真的需要这个作为参考类型:

class InventoryDictionary<U: Hashable, V: Equatable> : Equatable {
    var dictionary: [U: V] = [:]

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

请注意,我还从字典值中删除了可选项。它不应该在那里,除非你真的很想存储具有

nil
值的密钥。


2
投票

添加到 Sulthan 的回答中:

如果

U
的可散列性和
U
的公平性不是
InventoryDictionary
所固有的(即它们只需要符合
Hashable
Equatable
),那么你可以使用条件一致性:

// `U` has to be `Hashable` in any case, because it's used as a key
class InventoryDictionary<U: Hashable, V> {
    var dictionary: [U: V?] = [:]

    // ...
}

extension InventoryDictionary: Equatable where V: Equatable {}
extension InventoryDictionary: Hashable where V: Hashable {}
© www.soinside.com 2019 - 2024. All rights reserved.