Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 935
Jack Avatar asked Jul 27 '17 14:07

Jack


People also ask

What are constructors in Swift?

In Swift, an initializer is a special function that we use to create objects of a particular class, struct, or other type. Initializers are sometimes called constructors, because they “construct” objects.

Can struct have constructor in Swift?

Swift allows us to add new constructors to structs and still keep the compiler-generated ones by using extensions. If we extend a struct and define a custom initializer, the compiler can synthesize the default initializers and we get our custom constructor. In our example, we can add a custom init.

What does init () do in Swift?

Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.


1 Answers

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

like image 188
Maxime Avatar answered Nov 16 '22 03:11

Maxime