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 } } }
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.
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).
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.
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.
Use compactMapValues
:
dictionary.compactMapValues { $0 }
compactMapValues
has been introduced in Swift 5. For more info see Swift proposal SE-0218.
let json = [ "FirstName": "Anvar", "LastName": "Azizov", "Website": nil, "About": nil, ] let result = json.compactMapValues { $0 } print(result) // ["FirstName": "Anvar", "LastName": "Azizov"]
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"] }
I would do it by combining filter
with mapValues
:
dictionary.filter { $0.value != nil }.mapValues { $0! }
Use the above examples just replace let result
with
let result = json.filter { $0.value != nil }.mapValues { $0! }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With