Search code examples
jsonswiftswift3jsondecoder

JSONDecoder() deal with Null values only in Swift


Here is the JSON response I have.

Struct:

struct Welcome: Codable {
    let name: String
    let id: Int
}

JSON:

{
    "name": "Apple",
    "id": 23
}

This is the structure of JSON but the name will be null sometimes. So, I want to replace with default string value instead of null. Because to avoid app crash in future.

{
    "name": null,
    "id": 23
}

If the name is null then I want to give default value like "orange" for the property name only. I don't want to do anything with id.

I referred some SO answers are confusing and working with all properties in init instead of selected property. This is not possible for me because I have 200's of JSON properties with 50 types will be null or will have value..

How can I do it? Thanks in advance.


Solution

  • You can (kind of) achieve that by making a wrapper:

    struct Welcome: Codable {
        private let name: String? // <- This should be optional, otherwise it will fail decoding
        var defaultedName: String { name ?? "Orange" }
    
        let id: Int
    }
    

    This will also ensures that server never gets default value.