I have created a model to map my Api response to the swift struct with Codable protocol. but it always return nil. Note: - if i remove the isSelected from the model it works perfect. But I need this key to manage the selection from user. Also if i try this approach with class it always return self is immutable error. did any one face this issue also please help me to convert this code to swift class
struct CustomCodingKey:CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init?(intValue: Int) {
self.stringValue = String(intValue)
self.intValue = intValue
}
}
struct Field: Codable {
var type: String
var label: String
var name: String
var isSelected = false
init?(json: JSON) {
do {
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let decoder = JSONDecoder.init()
decoder.keyDecodingStrategy = .custom { keys -> CodingKey in
let key = keys.last!.stringValue.split(separator: "-").joined()
print(key)
return CustomCodingKey(stringValue: String(key))!
}
self = try decoder.decode(Field.self, from: data)
} catch {
return nil
}
}
var json: JSON {
do {
let data = try JSONEncoder().encode(self)
if let tempJson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? JSON {
return tempJson
}
return JSON()
} catch {
return JSON()
}
}
}