swift - 在执行可编码解码类型检查之前执行代码?
问题描述
decode
是否可以在调用之后但在执行类型检查之前执行代码?
let o7 = try decoder.decode(Organization.self, from: o6)
o7.configure()
return o7.save(on: request.db).flatMap { page in
return request.eventLoop.future("done")
}
它引发了一个错误:
捕获:typeMismatch(Swift.Dictionary<Swift.String, App.Event>, Swift.DecodingError.Context(codingPath: [ModelCodingKey(stringValue: "events", intValue: nil)], debugDescription: "Could not decode property",底层错误: 可选(Swift.DecodingError.keyNotFound(ModelCodingKey(stringValue: "events", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key ModelCodingKey(stringValue: "events", intValue :无)(“事件”)。”,基础错误:无)))))
o7
尚未匹配类型要求,但o7.configure()
是否需要执行所需的步骤,是否可以在configure
调用后“询问”检查类型?
这是 JSON:{"name": "xxx"}
这是类型:
final class Organization: Content {
var name: String?
var events: [String: Event]
}
如您所见,我需要初始化events
以避免 typeMismatch 错误。我用configure
方法做。
解决方案
尝试添加 CodingKeys,这将从可解码的 json 中排除“var events”。
final class Organization: Codable {
var name: String?
var events: [String: Event] = [:]
private enum CodingKeys: String, CodingKey {
case name
}
}
推荐阅读
- java - SQLException: ORA-02292: 违反完整性约束 (SCHOOL.STUDENT_STAGE_FK) - 找到子记录
- c++ - 未实例化的模板的 C++ 标准要求
- android - 自动为列表视图生成项目
- c# - 界面代码生成......Visual Studio 2015 中的快速操作和重构功能
- bash - 如何使文件夹仅在用户运行脚本时可访问
- r - 添加一列,将另一列分成n个块,R
- python - 如何使用 NAO 机器人进行演讲演示?
- laravel - Laravel 5.7,高级 where or and loop 困境
- mysql - 如何从 MySQL 数据库中的所有表中删除特定行?
- swift - Swift 测试非标量类型