Like multiple init () with Swift

Is it possible, if so, to have multiple init without a parameter, in a class like this (the line is just an example):

aVar: String init() { aVar = "simple init" } initWithAGoodVar() { aVar = "Good Var!" } initWithFooBar() { aVar = "Foo Bar" } 
+6
source share
4 answers

You cannot have multiple init without parameters, since it would be ambiguous which init method you would like to use. Alternatively, you can either pass the initial values โ€‹โ€‹to the init method. Taking an example from your question:

 class MyClass { var myString: String init(myString: String) { self.myString = myString } } let a = MyClass(myString: "simple init") 

Or, if myString should only be specific values, you can use 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" 
+4
source

It is impossible to have multiple init, taking the same (or not) parameters.

But if you are looking for a way to create objects with predefined states, you can use the static factory methods:

 class Test { let aVar: String init(aVar: String) { self.aVar = aVar } static func initWithAGoodVar() -> Test { return Test(aVar: "Good Var!") } static func initWithFooBar() -> Test { return Test(aVar: "Foo Bar") } } let test = Test.initWithFooBar() println(test.aVar) // Prints: "Foo Bar" 
+2
source

initWithSomething is an Objective-C style, and it will not work exactly the same as in Swift.

In Swift, all initializers are called init and may optionally accept some parameters.

You can use default values, for example:

 class Example { var aVar: String init(goodVar : String = "Good Var!") { aVar = goodVar } } let example1 = Example() println(example1.aVar) // prints "Good Var!" 

However, this approach will not work exactly the same as in your example, because as soon as you enter the second init method, it is ambiguous that you wanted:

 class Example { var aVar: String init(goodVar : String = "Good Var!") { aVar = goodVar } init(fooBar : String = "Foo Bar") { aVar = fooBar } } let example1 = Example() // error: cannot invoke initializerโ€ฆ 

A better approach might be to use Swift enum :

 class Example { enum ExampleType : String { case GoodVar = "Good Var!" case FooBar = "Foo Bar" } var aVar: String init(type : ExampleType) { aVar = type.rawValue } } let example1 = Example(type: .GoodVar) println(example1.aVar) // "Good Var!" let example2 = Example(type: .FooBar) println(example2.aVar) // "Foo Bar" 

This approach will provide the necessary flexibility using the usual Swift syntax.

+1
source

You may have a different init with different parameters. When you create a new instance of your class, the init method is called with the arguments that you passed to

0
source

Source: https://habr.com/ru/post/988241/


All Articles