Swift: How to remove a null value from Dictionary?

Anvar Azizov picture Anvar Azizov · Nov 20, 2014 · Viewed 28.5k times · Source

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

Answer

Marián Černý picture Marián Černý · Sep 26, 2018

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! }