Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How have multiple init() with Swift

Tags:

swift

init

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"
}
like image 292
grominet Avatar asked May 30 '15 19:05

grominet


People also ask

How many types of init are there in Swift?

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.

What is super init in Swift?

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.

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.

What is a convenience init Swift?

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.


1 Answers

You cannot have multiple inits 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"
like image 125
ABakerSmith Avatar answered Oct 04 '22 14:10

ABakerSmith