I would like to do some initialization logic after the Swift Coding/Encoding feature has finished decoding a JSON.
struct MyStruct: Codable {
let id: Int
Use a factory method that first uses init(from:)
and then calls your custom initialization code
struct Foo: Decodable {
let name: String
let id: Int
var x: String!
private mutating func finalizeInit() {
self.x = "\(name) \(id)"
}
static func createFromJSON(_ data: Data) -> Foo? {
guard var f = try? JSONDecoder().decode(Foo.self, from: data) else {
return nil
}
f.finalizeInit()
return f
}
}
let sampleData = """
{ "name": "foo", "id": 42 }
""".data(using: .utf8)!
let f = Foo.createFromJSON(sampleData)