[英]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.