Tuesday, November 25, 2014

Strange Tales of Swift Initialization

Russ Bishop:

Swift appears to treat initialization quite differently than Objective-C, even though under the hood it is actually quite similar. They both use two-phase initialization, but Objective-C simply hides the first phase from you.

[…]

Objective-C slaps some zeros on it and calls it done. Swift has no choice but to offer you access to this initialization phase. And by offer I mean make you an offer you can’t refuse.

[…]

Once Swift has walked the class chain setting all properties to appropriate default values, even including partially executing your initializers up until the point where they call super, it then resumes executing initialization code starting from the most-derived superclass as it walks back up the chain.

[…]

If you have a funny suspicious feeling in the back of your mind right now congrats: you’re a seasoned Objective-C pro. A lot of classes in Objective-C don’t follow the proper rules for initialization and/or have incorrectly marked headers. This includes plenty of Apple’s own classes.

In other words, Swift’s strictness is causing crashes where there were none before, but this is only because of latent bugs in the frameworks. However, Swift’s initializer rules are also causing headaches and badly structured code.

1 Comment RSS · Twitter

Leave a Comment