Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to remove a null value from Dictionary?

I'm new in Swift and I have a problem with filtering NULL values from JSON file and setting it into Dictionary. I getting JSON response from the server with null values and it crashes my app.

Here is JSON response:

"FirstName": "Anvar", "LastName": "Azizov", "Website": null, "About": null, 

I will be very appreciated for help to deal with it.

UPD1: At this moment I decided to do it in a next way:

if let jsonResult = responseObject as? [String: AnyObject] {                         var jsonCleanDictionary = [String: AnyObject]()      for (key, value) in enumerate(jsonResult) {       if !(value.1 is NSNull) {          jsonCleanDictionary[value.0] = value.1       }     } } 
like image 576
Anvar Azizov Avatar asked Nov 20 '14 16:11

Anvar Azizov


People also ask

How do you clear a dictionary in Swift?

Removing Key-Value Pairs To remove a key-value pair from a dictionary, set the value of a key to nil with subscript syntax or use the . removeValue() method. To remove all the values in a dictionary, append . removeAll() to a dictionary.

Does null exist in Swift?

However there is another data type in Swift called Optional, whose default value is a null value ( nil ). You can use optional when you want a variable or constant contain no value in it. An optional type may contain a value or absent a value (a null value).

Why is dictionary unordered in Swift?

Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations. Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you can't insert a value of the wrong type into a collection by mistake.

How does dictionary work in Swift?

Swift 4 dictionaries use unique identifier known as a key to store a value which later can be referenced and looked up through the same key. Unlike items in an array, items in a dictionary do not have a specified order. You can use a dictionary when you need to look up values based on their identifiers.


2 Answers

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! } 
like image 100
Marián Černý Avatar answered Sep 17 '22 19:09

Marián Černý


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 } 
like image 20
Antonio Avatar answered Sep 20 '22 19:09

Antonio