Jack
Jack

Reputation: 321

Constructors in Swift

I need some help in constructors in swift. I am sorry, if this question is incorrect or repeated, but I didn't found an answer to my question in another links. So, I have a class

class myClass {
  override init(){
    print("Hello World")
  }
}

And I have an another class

class anotherClass {
 let variable = myClass()
 }

Could somebody correct this code? Because it gives me error. I don't know how to explain my question in Swift, because I am newbie. But I will try to explain it, I want to say that when I create an object of the class "myClass", firstly constructor should work and print "Hello World". Thank you!

Upvotes: 19

Views: 40438

Answers (2)

Muhammad Faraz Ali
Muhammad Faraz Ali

Reputation: 970

In myClass, there is no meaning of override before the init keyword because it's a Parent class itself and it does not inherited to any other class.So you habe to simply write:

class myClass {
  init(){
    print("Parent Class")
  }
}

subClass should be like:

class anotherClass {
 let sub=myClass()
}

Now if an instance of anotherClass is created ,it will call the create an instance of myClass inside the subClass and call the init() method of myClass and print "Hello World"

Note:

If anotherClass will be the child class of myClass then: subClass should be like:

class anotherClass {
 override init(){
    print("Child Class")
  }
}

Now if an instance of subClass is created ,it will call the subClass constructor first then the parent class constructor

var sub=anotherClass()
//Output
//Child class (1st)
//Parent Class (second)

But If you want to Access the init() method of Parent class before the subClass(es), you have to write super.init() inside the init() method of child class(es)

class anotherClass {
 override init(){
    super.init()     //Accessing the Parent class constructor
    print("Child Class")
  }
}

Output will be:

var sub=anotherClass()
//Output
//Parent Class (1st)
//Child class  (second)

Upvotes: 0

Maxime
Maxime

Reputation: 1392

Your init method shouldn't have override keyword as it's not a subclass :

class myClass {
  init(){
    print("Hello World")
  }
}

And if your class is a subcass, you have to call super.init() in your init() method

Upvotes: 42

Related Questions