Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift codable, Default Value to Class property when key missing in the JSON

As you know Codable is new stuff in swift 4, So we gonna move to this one from the older initialisation process for the Models. Usually we use the following Scenario

class LoginModal
{    
    let cashierType: NSNumber
    let status: NSNumber

    init(_ json: JSON)
    {
        let keys = Constants.LoginModal()

        cashierType = json[keys.cashierType].number ?? 0
        status = json[keys.status].number ?? 0
    }
}

In the JSON cashierType Key may missing, so we giving the default Value as 0

Now while doing this with Codable is quite easy, as following

class LoginModal: Coadable
{    
    let cashierType: NSNumber
    let status: NSNumber
}

as mentioned above keys may missing, but we don't want the Model Variables as optional, So How we can achieve this with Codable.

Thanks

like image 912
rinku khatri Avatar asked Nov 10 '18 07:11

rinku khatri


People also ask

How do you handle null in Codable Swift?

A null value (no string) is treated as nil by default so the decoding is supposed to succeed if the property is optional. By the way: You can omit the CodingKeys. If the name of the properties are the same as the keys you don't need explicit CodingsKeys .

What is Codable and Codable in Swift?

Codable; the data-parsing dream come true!Codable is the combined protocol of Swift's Decodable and Encodable protocols. Together they provide standard methods of decoding data for custom types and encoding data to be saved or transferred.

What does the Codable protocol do in Swift?

The Codable protocol in Swift is really a union of two protocols: Encodable and Decodable . These two protocols are used to indicate whether a certain struct, enum, or class, can be encoded into JSON data, or materialized from JSON data.


1 Answers

Use init(from decoder: Decoder) to set the default values in your model.

struct LoginModal: Codable {

    let cashierType: Int
    let status: Int

    enum CodingKeys: String, CodingKey {
        case cashierType = "cashierType"
        case status = "status"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.cashierType = try container.decodeIfPresent(Int.self, forKey: .cashierType) ?? 0
        self.status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
    }
}

Data Reading:

do {
        let data = //JSON Data from API
        let jsonData = try JSONDecoder().decode(LoginModal.self, from: data)
        print("\(jsonData.status) \(jsonData.cashierType)")
    } catch let error {
        print(error.localizedDescription)
    }
like image 181
Sateesh Yemireddi Avatar answered Oct 01 '22 22:10

Sateesh Yemireddi