Calling the parent constructor when initializing a subclass in Swift

I have several classes that inherit from a base class. Usually with C ++ classes, I used to overwrite the constructor in the children, and then called the parent.

Is there a way in Swift to call the parent constructor when initializing the subclass without overwriting it?

internal class A { init(aBool: Bool? = false) { ... } } class B: A { init(aString: String) { ... } } 

Given these two classes as an example, I would like to initialize B using the constructor of A:

 let obj = A(true) 
+5
source share
2 answers

Apple rules state that:

[S] ubclasses do not by default inherit their superclass initializers. However, superclass initializers are automatically inherited if certain conditions are met. In practice, this means that you do not need to write initializer overrides in many common scenarios and can inherit superclass initializers with minimal effort when it is safe.

Assuming that you provide default values ​​for any new properties that you enter in a subclass, the following two rules apply:

Rule 1: If your subclass does not define any assigned initializers, it will automatically inherit all of its initializers assigned to superclasses.

Rule 2: If your subclass provides the implementation of all initializers assigned to superclasses, either by inheriting them in accordance with rule 1, or by providing a custom implementation as part of the definition, then it automatically inherits all the convenience initializers of the superclass.

These rules apply even if your subclass adds additional convenience initializers.

What does all this mean? If you make your subclass B initializer of convenience, then B must inherit all A designated initializers.

 class B: A { convenience init(aString: String) { ... } } 
+7
source

If you make B init a convenience init , it will not mask the original init , and you can do it ...

 class A { var b: Bool? = nil init(aBool: Bool? = false) { self.b = aBool } } class B: A { var s: String? = nil convenience init(aString: String) { self.init(aBool: false) self.s = aString } } let obj1 = A(aBool: true) // obj1 is now an A, obviously. let obj2 = B(aBool: true) // obj2 is now a B 

You need to be careful by default or otherwise set all properties, though ...

Alternatively, you can override original init in B and just call super.init .

+2
source

Source: https://habr.com/ru/post/1243157/


All Articles