首页 > 解决方案 > Swift 等价于 Python Dictionary setdefault() 方法

问题描述

setdefault()如果字典中缺少键,则 Python 字典上的方法设置键的值并返回该值。参考

Swift 字典有类似的方法吗?

我试过这个:

var dic1 = ["a": 1]
let defVal = dic1["b", default: 2]
print(defVal) // prints 2
print(dic1) // prints ["a": 1]
// However, I need ["a": 1, "b": 2]

标签: pythonswiftdictionary

解决方案


这是声明了 setDefault 的扩展

extension Dictionary {
    mutating func setDefault(_ key: Key, value: Value) {
        if self[key] == nil {
           self[key] = value
        }
    }
}

例子

var d1: [String: Int] = ["A": 4]
d1["C"] = 13
d1.setDefault("B", value: 42)

print(d1)

输出

[“A”:4,“C”:13,“B”:42]


推荐阅读