我创建了一个模型来将我的 Api 响应映射到使用 Codable 协议的 swift 结构。但它总是返回零。注意: - 如果我从模型中删除 isSelected ,它会完美运行。但我需要这个密钥来管理用户的选择。此外,如果我在类中尝试这种方法,它总是返回 self is immutable 错误。有没有人遇到过这个问题也请帮我将此代码转换为 swift 类
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()
}
}
}