[英]Adding Key and Value to a Dictionary in Swift Based on Condition
我有以下代码,我想添加点赞和转发,前提是点赞不为零。 我想出了以下代码,但想知道是否有更好的方法。
func toDictionary() -> [String: Any] {
var tweetDict = ["userId": userId, "text": text, "dateCreated": dateCreated, "dateUpdated": dateUpdated] as [String : Any]
if let likes {
tweetDict["likes"] = likes
}
if let retweets {
tweetDict["retweets"] = retweets
}
return tweetDict
}
我可以将喜欢和转推初始化为一个空数组,但是当我将它保存在 Firebase 中时,它会在 Firestore 数据库中创建一个空数组。 我认为 Firebase 中的额外键即使是空的也会占用很少的空间(除非我的理解是错误的),而且我不确定在 Firebase 中存储空数组是否是个好主意。
我能想到的最简单的是向字典添加扩展名:
extension Dictionary {
mutating func updateValueIfNotNil(_ value: Value?, forKey: Key) {
guard let value = value else {
return
}
updateValue(value, forKey: forKey)
}
}
如果提供的值为 nil,则忽略,否则执行正常的updateValue
(与赋值相同):
var tweetDict = ["userId": "aa", "text": "bb", "dateCreated": Date(), "dateUpdated": Date()] as [String : Any]
let notNil = "something"
let isNil: String? = nil
tweetDict.updateValueIfNotNil(notNil, forKey: "retweets")
tweetDict.updateValueIfNotNil(isNil, forKey: "likes")
print(tweetDict)
会打印
["userId": "aa", "text": "bb", "dateCreated": 2022-07-13 20:13:46 +0000, "dateUpdated": 2022-07-13 20:13:46 +0000, "retweets": "something"]
(即没有添加“喜欢”,因为它们的值为零)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.