Search code examples
iosswiftjsondecoder

Convert null values to default strings in parsing JSON using JSONDecoder in Swift


I am trying to parse some JSON in Swift using JSONDecoder where the JSON occasionally has null values. I would like to put in a default instead. The following allows me to handle it but the nulls cause problems later.

struct Book: Codable {
        let title : String
        let author: String?
    }

Is there a way to do something like (following does not compile), perhaps using an initializer?:

struct Book: Codable {
        let title : String
        let author: String ?? "unknown"
    }

Thanks for any suggestions


Solution

  • This could be address by manually decoding as described here.

    The other way to go would be to have the stored properties reflect the data exactly, and then have a computed var for the case of providing a non-optional value.

    struct Book: Codable {
        let title : String
        let author: String?
    
        var displayAuthor: String {
            return author ?? "unknown"
        }
    }
    

    The other reason this might be appealing is it preserves the optional value should you need to check if the value exists at all in the future.