If I have a struct called Person
struct Person: Codable {
var name: String
}
I want it to print "Person initialised" every time a Person
is initialised using the synthesised init(from decoder:)
method which comes automatically when you conform to Codable
. Is there any way to get this behaviour without implementing a custom init(from decoder:)
method? Sort of "appending" code to execute after the synthesised init(from decoder:)
is called.
In essence something like:
protocol Announce: Codable { }
extension Announce {
init(from decoder: Decoder) throws {
try self.init(from: decoder) // I want this to call the synthesised one you get by conforming to Codable, NOT itself
print("Person initialised using synthesised init")
}
}
The reason I don't want to implement my own initialiser is because I don't want to rewrite everything the compiler is already going to do for me for free just to add a simple print("Person initialised")
, specially if the struct
becomes more complex.
Please let me know if I can achieve this sort of behaviour without providing my own implementation of init(from decoder:)
.
Thanks in advance!