问题描述
是否可以在调用 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")
}
caught: typeMismatch(Swift.Dictionary
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
}
}