Home > Net >  Adding Key and Value to a Dictionary in Swift Based on Condition
Adding Key and Value to a Dictionary in Swift Based on Condition

Time:07-14

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. 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.

CodePudding user response:

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):

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"]

(i.e. "likes" were not added, since their value is nil)

  • Related