Init to Winit: Building Success with Swift Class Initializers
The other day, a developer in one of the IRC chat rooms attempted to subclass NSWindowController in Swift. No matter how hard he tried, he couldn't get his convenience initializer to work. In Objective-C this is a no-brainer. If a superclass establishes, for example, initWithWindowNibName:owner:, the child class can automatically use that initializer. In Swift, it takes a bit of work to arrive at the same place. This write-up introduces the know-how you need to leverage these built-in convenience APIs.
Initializers
In development, initializers prepare language elements for use. They establish default values for stored properties and perform basic setup tasks. Swift enables you to initialize instances of classes, structures, and enumerations, but it is the initializers in classes that prove the trickiest to work with. That's because classes adopt inheritance, enabling subclasses to inherit the features and initializers of their superclass.
A normal Swift instance initializer follows three basic steps:
- Initialize any instance variables created by your class to a default starting state.
- Call the superclass (if one exists) to initialize its instance variables. Yes, in Swift, you perform this action after you set up locally declared variables. This ordering ensures the class storage is consistent at all hierarchical levels.
- Perform any other setup duties (if any) required by your instance. Here is where you can override any inherited properties and call instance methods, and freely refer to self as a value.
The MyWindowControllerSubclass class in Figure 1 has superficially followed this standard pattern, adding a custom init() method in addition to the required init(coder:). This method sets up its new local variable and then calls super.init(). Despite this pattern, Swift won't build an instance using the parent's convenience initializer, the way it would in the Objective C code this example mirrors.
Figure 1 Convenience initializers may not be immediately available for use by subclasses. The required modifier on line 19 indicates an initializer that must be implemented wherever uninitialized storage is added in subclasses.
You might think, "Let me just create an initializer that redirects to the parent." As you see in Figure 2, that approach won't work either.
Figure 2 Designated initializers cannot call convenience initializers. They must call designated initializers in the superclass.
You must proceed carefully when working with Swift class initializers. If Objective-C is a big, warm, fuzzy teddy bear when it comes to initializers, Swift is a bespectacled, whip-carrying, leather-clad librarian with an attitude. Unless you follow certain rules, you find yourself fighting against the patterns that ensure your objects are initialized safely and consistently.
Designated and Convenience Initializers
Swift (and Objective-C, and many modern languages for that matter) uses two distinct initializer patterns. A designated initializer follows the three steps you just read about. It exhaustively establishes default values for all storage introduced by the class declaration.
class RootClass { var a : Int // local storage init(a : Int) { self.a = a // initialization } }
When you introduce a subclass, the subclass's designated initializer sets its new properties first and then calls an initializer that walks up the superclass chain.
class ChildClass : RootClass { var b : Int // new subclass storage init(a : Int, b : Int) { self.b = b // initialization super.init(a:a) // redirect to superclass } }
A convenience initializer provides a secondary construction utility. Although designated initializers should be few and functionally complete, a convenience initializer enables you to piggyback on designated initializers. They provide constructors that are shorter to call or provide an indirect initialization mechanism.
class ChildClass : RootClass { var b : Int init(a : Int, b : Int) { self.b = b super.init(a:a) } // This convenience method requires only one parameter override convenience init(a: Int) { self.init(a:a, b:0) } }
Convenience initializers are, as their name suggests, convenient or handy. For example, you might pass a string that holds the path to a nib for a view class as in the examples in Figures 1 and 2. Or you might provide an offset relative to the current time (timeIntervalSinceNow) in place of the canonical reference time (timeIntervalSinceReferenceDate) that an NSDate normally uses to set itself up.
Convenience initializers provide entry points built around the typical API needs of a client rather than the internal structure of the class. They offer a developer-friendly way to create shortcut patterns for instance construction.
The Rules of Initializers
Swift's documentation officially defines three initializer rules:
- Designated initializers in subclasses must call designated initializers in superclasses. This is the rule broken in Figure 2, which attempts to call a convenience initializer from a designated one. Designated initializers always delegate upward to other designated initializers and never to convenience ones.
- Convenience initializers must call other initializers (designated or convenience) defined in the same class. Convenience initializers always delegate sideways and may not walk up the chain to a superclass.
- Convenience initializers must end up redirecting to a designated initializer in the same class. Eventually the initializer chain from Rule #2 must end, and it must do so by calling a designated initializer declared in the sameclass as itself.
- Any class that inherits or overrides its superclass's designated initializers may inherit its convenience initializers. Classes inherit designated initializers if they don't add new variables that need initialization. This applies to classes that don't define additional stored properties and classes whose new properties use default values defined outside initializers, for example var x : Int = 5.
No matter how much you keep delegating sideways, eventually you end up at a designated initializer that walks up the chain. And because designated initializers cannot call convenience initializers, that chain stops wandering as soon as you hit the designated item. By Rule #1, you walk up the class tree in a straight path of designated initializers.
There's one more rule from the Automatic Initializer Inheritance section that goes like this:
Rule #4 works because the convenience initializers defined in the superclass always have a local designated initializer to end up at. Rule #2 ensures that the inherited initializers hop sideways through the child class. Because the possible initializer endpoints from Rules #1 and #3 are well defined, the inherited initializers are guaranteed to end up at a designated initializer in the child class.
Figure 3 shows what that solution looks like for the MyWindowControllerSubclass implementation from Figures 1 and 2. The subclass initializer on line 80 now compiles and calls the designated initializers in the subclass. The newVar instance variable now initializes properly, even when calling the convenience initializer.
Figure 3 By implementing all designated initializers, a child class can inherit the behavior of a parent's convenience initializer.
Finding Initializers
The example from Figure 3 highlights a potential peril of this process. As you see in Figure 4, the NSWindowController class declares two designated initializers, not three.
Figure 4 The NSWindowController class. You view these details by Command-Clicking the class name in your Xcode source code.
If you override just these two initializers (see Figure 5), you end up with a compile-time error. You're responsible for overriding all potential initializer endpoints in your superclasses that the convenience initializer may use.
Figure 5 All three initializers must be overridden to use the convenience initializer.
If you explore further into the class hierarchy to NSResponder (see Figure 6) and then NSObject, you discover the third designated initializer. You must also define init()to use the init(windowNibName:) convenience initializer. After you do so, you return to the successful results in Figure 4.
Figure 6 NSResponder defines a designated init() initializer.
By understanding the rules and flow of the initializers, you take charge of your application and ensure that you can use and subclass Cocoa and Cocoa Touch classes exactly as you need.
Wrap-Up
Want to learn more about this topic? Make sure to check out the “Initialization” section in the official Swift Programming Language book from Apple. This volume is available for free from the iBookstore and offers a must-read resource for any new Swift developer.
Thanks to Ken Ferry and Kevin Ballard for patient and extensive help in getting me up to speed on this topic. Mistakes are mine; any wisdom is theirs. Thanks also to Mike Ash for helping read this write-up.
About the author: Erica Sadun
Erica Sadun is the bestselling author, coauthor, and contributor to several dozen books on programming, digital video and photography, and web design, including the widely popular The iOS Developer's Cookbook. In addition to being the author of dozens of iOS-native applications, Erica holds a Ph.D. in computer science from Georgia Tech's Graphics, Visualization and Usability Center.