17

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!

Jack
  • 291
  • 2
  • 6
  • 12
  • 6
    It's fairly unhelpful to say that you're getting an error, then not say what the error is. – Carcigenicate Jul 27 '17 at 14:26
  • 3
    Get rid of `override`. You aren't overriding anything. Class names should start with uppercase letters. – vacawama Jul 27 '17 at 14:26
  • Remove the `override` keyword in the first class. Unlike in ObjC when all classes ultimately inherit from `NSObject`, Swift classes can have no superclass at all. You were not overriding anything – Code Different Jul 27 '17 at 14:28

2 Answers2

37

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

Maxime
  • 1,332
  • 1
  • 15
  • 43
0

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)