Codable in Swift

Best Tutorial i Found for Codable:

Coable is for converting JSON data to object (decodable) and object into JSON format (encodable)

struct Loan: Codable {

    var name: String

    var country: String

    var use: String

    var amount: Int

}

If key name in JSON (API) change we can use CodingsKeys protocol to avoid change name everywhere or to maintain proper naming conventions.

struct Loan: Codable {

    var name: String

    var country: String

    var use: String

    var amount: Int

    enum CodingKeys: String, CodingKey {

        case name

        case country

        case use

        case amount = “loan_amount”

    }

}

let json = try JSONSerialization.jsonObject(with: dataToSend, options: []) as? [String : Any]

// use this to get data in JSON format

Be CareFul : Using optionals and non optionals in your models

There is a trick for you to keep using the codable protocol frequently, and not keeping the following in mind may cause you problems in the future and potentially in the live app.

1- If your model contains non-optional property and your JSON does not contain that property or there is a spelling mismatch,Even a single missing key will cause your parsing to fail.

2- If your properties are optional then missing properties will be nil. But your models will be populated accordingly.

3- In case all your properties are optional then even an empty json will parse successfully. It will return you an instance of your object though all of its properties will be nil.

Consider the following Example

Image for post

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s