[英]How do I specify more than one type to decode in the enum CodingKeys when using Codable?
[英]Error while I'm trying to decode using CodingKeys
这是我的结构
import Foundation
struct Settings: Hashable, Decodable{
var Id = UUID()
var userNotificationId : Int
}
编码键
private enum CodingKeys: String, CodingKey{
**case userNotificationId = "usuarioNotificacionMovilId"** (this is the line that gets me errors)
}
在里面
init(userNotificationId: Int){
self.userNotificationId = userNotificationId
}
解码器
init(from decoder: Decoder) throws{
let container = try decoder.container(keyedBy: CodingKeys.self)
userNotificationId = try container.decodeIfPresent(Int.self, forKey: .userNotificationId) ?? 0
}
编码器
init(from encoder: Encoder) throws{
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(userNotificationId, forKey: .userNotificationId)
}
我在编码方法中收到以下错误
在初始化所有存储的属性之前使用“self”
init(from encoder: Encoder)
应该是什么? 您不符合Encodable
,如果符合,则需要实现func encode(to encoder: Encoder) throws
,而不是另一个初始化器。
也就是说,您对init(from decoder: Decoder) throws
的显式实现与编译器为您合成的内容没有什么不同,因此最好也完全删除它。
struct Settings: Hashable, Decodable {
let id = UUID()
let userNotificationId: Int
private enum CodingKeys: String, CodingKey{
case userNotificationId = "usuarioNotificacionMovilId"
}
init(userNotificationId: Int) {
self.userNotificationId = userNotificationId
}
}
可能就是您所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.