覆盖 Swift 中字典的默认行为以忽略零值?

Overriding default behaviour of dictionaries in Swift to ignore zero values?

我想创建一个数据类型,它的作用类似于字典,但会忽略任何值为零的键,例如考虑一个假设的例子:

typealias SpecialDict = Dictionary<String,Int>
let testA: SpecialDict = ["a":1, "b":4, "c":0]
let testB: SpecialDict = ["a":1, "b":4]
testA == testB // should evaluate as true

我不确定这样做是否更好:

或者,创建具有固定键列表的字典的方法(即您不能添加或删除键,只能更改它们的值)也可以。

我想说最简单的方法是创建您自己的 struct,它的行为方式如您所愿。我会做这样的事情:

struct MyDict {

    private var dictionary = [String: Int]()

    subscript(key: String) -> Int? {
        get {
            return dictionary[key]
        }
        set {
            if newValue! != 0 {
                dictionary[key] = newValue
            } else {
                dictionary.removeValueForKey(key)
            }
        }
    }
}

但请记住,此结构不是字典,因此您必须实现所需的每个功能。