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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With