简体   繁体   English

根据条件在 Swift 中向字典添加键和值

[英]Adding Key and Value to a Dictionary in Swift Based on Condition

I have the following code and I want to add the likes and retweets, only if the likes are not nil.我有以下代码,我想添加点赞和转发,前提是点赞不为零。 I came up with the following code but was wondering if there is a better way.我想出了以下代码,但想知道是否有更好的方法。

 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
                
            }

I can initialize likes and retweets to be an empty array but then when I save it in Firebase it create an empty array in Firestore database.我可以将喜欢和转推初始化为一个空数组,但是当我将它保存在 Firebase 中时,它会在 Firestore 数据库中创建一个空数组。 I think that extra key in Firebase will take up little space even though it is empty (unless my understanding is wrong) and I am not sure if storing empty array in Firebase is a good idea.我认为 Firebase 中的额外键即使是空的也会占用很少的空间(除非我的理解是错误的),而且我不确定在 Firebase 中存储空数组是否是个好主意。

Simplest I can think of is add an extension to dictionary:我能想到的最简单的是向字典添加扩展名:

extension Dictionary {
    
    mutating func updateValueIfNotNil(_ value: Value?, forKey: Key) {
        guard let value = value else {
            return
        }
        
        updateValue(value, forKey: forKey)
    }
}

If the provided value is nil, it's ignored, otherwise normal updateValue is performed (which is the same as assigning a value):如果提供的值为 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) 

would print会打印

["userId": "aa", "text": "bb", "dateCreated": 2022-07-13 20:13:46 +0000, "dateUpdated": 2022-07-13 20:13:46 +0000, "retweets": "something"]

(ie "likes" were not added, since their value is nil) (即没有添加“喜欢”,因为它们的值为零)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM