Is it possible, if yes how, to have multiple init without parameter, in a Class like this (the string is just an exemple):
aVar: String
init() {
aVar = "simple init"
}
initWithAGoodVar() {
aVar = "Good Var!"
}
initWithFooBar() {
aVar = "Foo Bar"
}
Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. These are known as designated initializers and convenience initializers.
super is just reference to superclass and that superclass have init method, so by calling super.init() you call init method of superclass without parameters. If init method of superclass have parameters class Animal { init(name: String) { } } you must pass parameters to this method class Cat: Animal { init() { super.
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.
convenience init : Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer's parameters set to default values.
You cannot have multiple init
s without parameters since it would be ambiguous which init
method you wanted to use. As an alternative you could either pass the initial values to the init
method. Taking the example from your question:
class MyClass {
var myString: String
init(myString: String) {
self.myString = myString
}
}
let a = MyClass(myString: "simple init")
Or, if myString
is only supposed to be certain values, you could use an enum
:
class MyOtherClass {
enum MyEnum: String {
case Simple = "Simple"
case GoodVar = "GoodVar"
case FooBar = "FooBar"
}
var myString: String
init(arg: MyEnum) {
myString = arg.rawValue
}
}
let b = MyOtherClass(arg: .GoodVar)
println(b.myString) // "GoodVar"
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