Swift: How to remove a null value from Dictionary?
You can create an array containing the keys whose corresponding values are nil:
let keysToRemove = dict.keys.array.filter { dict[$0]! == nil }
and next loop through all elements of that array and remove the keys from the dictionary:
for key in keysToRemove {
dict.removeValueForKey(key)
}
Update 2017.01.17
The force unwrapping operator is a bit ugly, although safe, as explained in the comments. There are probably several other ways to achieve the same result, a better-looking way of the same method is:
let keysToRemove = dict.keys.filter {
guard let value = dict[$0] else { return false }
return value == nil
}
Swift 5
Use compactMapValues
:
dictionary.compactMapValues { $0 }
compactMapValues
has been introduced in Swift 5. For more info see Swift proposal SE-0218.
Example with dictionary
let json = [
"FirstName": "Anvar",
"LastName": "Azizov",
"Website": nil,
"About": nil,
]
let result = json.compactMapValues { $0 }
print(result) // ["FirstName": "Anvar", "LastName": "Azizov"]
Example including JSON parsing
let jsonText = """
{
"FirstName": "Anvar",
"LastName": "Azizov",
"Website": null,
"About": null
}
"""
let data = jsonText.data(using: .utf8)!
let json = try? JSONSerialization.jsonObject(with: data, options: [])
if let json = json as? [String: Any?] {
let result = json.compactMapValues { $0 }
print(result) // ["FirstName": "Anvar", "LastName": "Azizov"]
}
Swift 4
I would do it by combining filter
with mapValues
:
dictionary.filter { $0.value != nil }.mapValues { $0! }
Examples
Use the above examples just replace let result
with
let result = json.filter { $0.value != nil }.mapValues { $0! }