'How to remove empty key value pair from dictionary in swift

Lets say I have a dictionary

let dic = ["a": "1", "b": "2", "c": "", "d": "3"]

I want to delete "c" key with its value



Solution 1:[1]

This should do.

let dic = ["a": "1", "b": "2", "c": "", "d": "3"]

let filteredDict = dic.filter( { !$0.value.isEmpty })
print(filteredDict) // Prints ["a": "1", "b": "2", "d": "3"]

Edit: David's answer is the one you go for if you only want to delete a specific key. But that makes no sense because if you knew what key to delete, would it matter if it is empty or not? I am assuming that you do not know which key(s) is empty, in which case you would have to do like how it is shown in this answer.

Solution 2:[2]

Here is an alternative using filter with a forEach loop that updates the original dictionary:

var dic = ["a": "1", "b": "2", "c": "", "d": "3"]

dic.filter({$0.value.isEmpty}).forEach( { dic[$0.key] = nil})

Solution 3:[3]

You just need to set the value of the key you want to remove to nil. Just make sure that you declare the dictionary as mutable using the var keyword.

var dic = ["a": "1", "b": "2", "c": "", "d": "3"]
dic["c"] = nil
print(dic) //["a": "1", "b": "2", "d": "3"]

Note: This doesn't work if Value is optional.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user28434'mstep
Solution 2 rmaddy
Solution 3 ScottyBlades