Tip: Swift Common Initializer Pattern
Check this out for a useful tip to reduce duplication in your Swift applications.
Join the DZone community and get the full member experience.Join For Free
Here’s a handy tip for reducing duplication and/or frustration with your initializers:
Swift has a very well thought-out initializer system in place. With options such as designated and convenience initializers, one must ensure all properties have values since the compiler will make sure of it. Take a look at my other post for more details.
… Your first thought may be: why not wrap it in a function and call the function from both initializers? Nope. Can’t do that because you cannot reference “self” for the method call before calling “super.init“, and you can’t call the method after initialization either until you’ve initialized all properties – catch 22:
So you end up either tedious and violating DRY, or using var/lazy and violating immutability, yes, we find that niggling on a fairly regular basis. Skipping past the narrative (follow the link if you wish) Here Is The Solution.
Wow, nice! Solves the redundant code problem while still abiding by the initialization rules. It’s using a static function to initialize the properties, which indeed can be called before the class is initialized (since it’s static and not using self).
Secondly, it’s returning a tuple to initialize multiple properties at once. That’s cool too! And for the sugar on top, it’s using a “typealias” like “My” or “I” to keep the static calls short.
We like it! Very Swifty feeling, isn’t it?
h/t: This Week In Swift!
For another interesting initialization pattern, check out: Swift: Configuring a Constant Using Shorthand Argument Names.
It’s a common pattern in Swift (and a really nice one!) to configure constants right when they are initialized in a closure vs later on in a viewDidLoad or another such method … I’ve always found it kind of awkward to name another UIView in the closure. Now there is a “purpleView” and a “view”. Should “view” actually be named “purpleView” also? I haven’t figured out a good solution for the naming problem here. So I was super excited to see the tweet that uses $0 instead of bothering to name the variable!
Not quite sure whether we actually prefer this, but it is more concise. Also, check out the Configurable extension!
Published at DZone with permission of Alex Curylo, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.