首页 > 解决方案 > 在执行可编码解码类型检查之前执行代码?

问题描述

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方法做。

标签: swiftcodablevapor

解决方案


尝试添加 CodingKeys,这将从可解码的 json 中排除“var events”。

final class Organization: Codable {
    var name: String?
    var events: [String: Event] = [:]
    
    private enum CodingKeys: String, CodingKey {
        case name
    }
}

推荐阅读