I have a Codable object model that I'm retrieving with Alamofire. However I'd like to add extra boolean variable in the model that's not the part of the model on server side, is that possible on iOS?
To conform to Codable protocol, I need to add it to CodingKeys enum, but if I do, it tries to parse property from server that's not there.
You can simply give a default value to the property that should only exist in your iOS app's model class, then omit that property's name from the your CodingKey
enum
and your model class/struct will still conform to Codable
without having to encode/decode that property to/from JSON.
You can find an example of this below.
struct Person: Decodable {
let name:String
let age:Int
var cached = false //not part of the JSON
enum CodingKeys:String,CodingKey {
case name, age
}
}
let json = """
{"name":"John",
"age":22}
"""
do {
let person = try JSONDecoder().decode(Person.self,from: json.data(using: .utf8)!)
print(person) // Person(name: "John", age: 22, cached: false)
} catch {
print(error)
}