0

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!

rayaantaneja
  • 1,182
  • 7
  • 18
  • 2
    Very reasonable but, I believe, not possible, exactly because of the way the initializer is synthesized and injected for you. It's all or nothing: you accept the synthesized implementation or you write your own. You are imagining a sort of "inheritance" or "delegation" that just doesn't exist. – matt Aug 04 '21 at 10:09
  • But that particular init is only used when decoding so you always know when Person objects are created with that init, when you do JSONDecoder().decode(Person.self,…) (or similar) – Joakim Danielson Aug 04 '21 at 10:30

0 Answers0