swift - 尝试使用 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
}
}
可能就是你所需要的。
推荐阅读
- sql-server - 在 SQL Server 中选择记录后更新记录
- python - 如何大写颠倒的元音?
- streaming - 检查点恢复时,flink kafkaproducer 以仅一次模式发送重复消息
- c# - 如何对齐两个元素与约束?
- apex - APEX CPU 限制。在顶点类中使用地图而不是列表
- python - python cgi PermissionError: [Errno 13] 权限被拒绝:
- ruby-on-rails - 当我尝试设置 Rails 项目时出了什么问题?
- c++ - 尝试读取 .txt 文件并根据用户输入的字母提取特定行
- r - 当模型包含交互时,mlogit 模型中的奇异性问题
- xamarin - Xamarin Forms Android 应用程序在启动时失败:无法检测 [class] 何时激活/停用..实现 IActivationForViewFetcher