Super init constructor in Swift

I worked with Objective-c with the following code in my constructor for the NSObject class:

- (id)init { self = [super init] ; return self; } 

How to use it in Swift?

I tried to do this:

 override init() { self = super.init() return self; } 

I get two errors:

 cannot assign value self is immutable nil is the only return value permitted in this initializer 
+5
source share
4 answers

You cannot assign self to Swift. Just use

 super.init() 

You also do not return anything. Constructors are of type void (in C lingo).

+12
source

The Swift initialization sequence is slightly different from Objective-C,

 class BaseClass { var value : String init () { value = "hello" } } 

subclass below.

 class SubClass : BaseClass { var subVar : String let subInt : Int override init() { subVar = "world" subInt = 2015 super.init() value = "hello world 2015" // optional, change the value of superclass } } 

Initialization Sequence:

  • Initialize a subclass of var or let,
  • Call super.init () if the class has a superclass,
  • Change the value of the superclass if you want to do this.

I think your code is:

 override init() { self = super.init() //just call super.init(), do not assign it to self return self; //it is unnecessary to return self } 

We must remember the initialization of all var or let classes.

+5
source

In Swift, you do not assign or return self . In addition, you need to call super.init() after personalized initialization. Ie, if your Objective-C code looked something like this:

 - (instancetype)init { if (self = [super init]) { someProperty = 42; } } 

then the equivalent in Swift will be

 init() { self.someProperty = 42 super.init() } 

The reason for this is indicated in the Apple documentation :

Security Check 1 The designated initializer must ensure that all properties introduced by its class are initialized before it delegates to the superclass initializer.

As mentioned above, the memory for an object is considered only fully initialized, as soon as the initial state of all properties stored by it is known. In order for this rule to be satisfied, the designated initializer must ensure that all of its own properties are initialized before it disconnects the chain.

+1
source

Apple document, Swift programming language, on initialization . Example in the document.

 class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } 
0
source

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


All Articles