Thursday, August 3, 2017

“required” Swift Initializers and Decodable

Jordan Rose (via Jesse Squires):

The initializer is required, right? So all subclasses need to have access to it. But the implementation we provided here might not make sense for all subclasses—what if VerySpecialSubclassOfPoint doesn’t have an init(x:y:) initializer? Normally, the compiler checks for this situation and makes the subclass reimplement the required initializer…but that only works if the required initializers are all known up front. So it can’t allow this new required initializer to go by, because someone might try to call it dynamically on a subclass.

[…]

required initializers are like methods: they may require dynamic dispatch. That means that they get an entry in the class’s dynamic dispatch table, commonly known as its vtable. Unlike Objective-C method tables, vtables aren’t set up to have entries arbitrarily added at run time

[…]

In most cases you don’t care about hypothetical subclasses or invoking init(from:) on some dynamic Point type. If there was a way to mark init(from:) as something that was always available on subclasses, but dynamically checked to see if it was okay, we’d be good.

[…]

For more information on this I suggest checking out my write-up of some of our initialization model problems.

Comments RSS · Twitter

Leave a Comment