Search code examples
swiftguard

How to check JSON can be converted to dictionary in Swift?


enter image description here

Tried this, but get error:

var d = (try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as [String: String]
guard let d2 = d else {
    return
}

Solution

  • The right tool here is JSONDecoder, not JSONSerialization:

    let d = try JSONDecoder().decode([String: String].self, data)
    

    .mutableContainers doesn't make sense when converting to a Swift Dictionary. That causes it to create NSMutableDictionary objects, which will just be converted to [String: String] exactly the same as without .mutableContainers (but possibly with an extra copy step).