python - 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]
解决方案
这是声明了 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]
推荐阅读
- python - 将行附加到具有不相等列的 Dataframe 的最有效方法
- math - 对于 smoothstep 函数 glsl,edge0 大于或等于 edge1 是什么情况
- email - 为什么 sentDate 和 receivedDate 有时是相等的?
- python-3.x - 请求获取和烧瓶邮件 Python
- java - 如何从 android .apk 文件中的资产中解压缩 zip 文件
- mongodb - 如何在没有 db.collection.stats() 的情况下将集合名称映射到 WiredTiger URL
- php - 用于自动登录用户的 cookie 的安全性如何?
- python - 为什么我的 ipywidget 观察在单个状态更改时被多次调用?
- python - 成功切换到 iframe 但找不到元素
- python - RuntimeError:梯度计算所需的变量之一已被就地操作修改