How have multiple init() with Swift

grominet picture grominet · May 30, 2015 · Viewed 12k times · Source

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"
}

Answer

ABakerSmith picture ABakerSmith · May 30, 2015

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"