Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach to create Non-optional Codable with `default values` in swift

I know the basic concept of class and struct but which is more effective to create models for API to fetch data and tell me with pros and cons.

Previously i don't use optional for models. Instead i give it some value. ie

class CompanyInfo : Codable {
    var NameEn : String = ""
    var CityEn : String = ""
    var Website : String = ""
    var Email : String = ""
    var Phone : String = ""
    var Fax : String = ""
}

but when it get some null value from API. ie "Fax": null then App get crashed because it can't parse data with following line

let data = try JSONDecoder().decode(dataModel.self, from: dataSet)

what is the best way to deffine a model so i don't need to unwrap optional or give it default value.

like image 885
Wahab Khan Jadon Avatar asked Mar 03 '23 05:03

Wahab Khan Jadon


1 Answers

You can implement a custom decoder with default values:

class CompanyInfo : Codable {
    var NameEn: String
    var CityEn: String
    var Website: String
    var Email: String
    var Phone: String
    var Fax: String
    
    required init(from decoder: Decoder) throws {
        do {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            self.NameEn = try container.decodeIfPresent(String.self, forKey: .NameEn) ?? "Default"
            self.CityEn = try container.decodeIfPresent(String.self, forKey: .CityEn) ?? "Default"
            self.Website = try container.decodeIfPresent(String.self, forKey: .Website) ?? "Default"
            self.Email = try container.decodeIfPresent(String.self, forKey: .Email) ?? "Default"
            self.Phone = try container.decodeIfPresent(String.self, forKey: .Phone) ?? "Default"
            self.Fax = try container.decodeIfPresent(String.self, forKey: .Fax) ?? "Default"
        }
    }
}

Unrelated to question, but important Note:

In Swift, only Types names should start with a capital letter. If you continue naming variables like this, you will have a serious refactoring issue one day if you decide to use CoreData or working with other Swift developers.

like image 55
Mojtaba Hosseini Avatar answered May 10 '23 13:05

Mojtaba Hosseini