Wednesday, 16 September 2015

Initializers - Swift

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:
  1. Initialize any instance variables created by your class to a default starting state.
  2. 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.
  3. 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 toself 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) {
super.init(a:a) // redirect to superclass
self.b = b // initialization }
}
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
self.b = b
init(a : Int, b : Int) {
// This convenience method requires only one parameter
super.init(a:a) }
self.init(a:a, b:0)
override convenience init(a: Int) { }
}
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 anNSDate 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:
  1. 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.
  2. 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.
  3. 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.
  4. 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:
  5. 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.

Gopinath TB, 
CEO, Meteora Gaming
www.meteoragaming.com



No comments:

Post a Comment