Jack Jack - 1 year ago 165
Swift Question

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!

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download