Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift create custom initializer without parameters with custom name

Tags:

swift

I want to create init for my class that might look something like this:

initWithSomeMode { // Not compilable
    self.init()
    self.customSetup()
}

Of course code above will not work, I just want to show what I want to achieve.

I can only see convenience init in Swift class, but in that case I need to add parameters, but I don't need them.

So, I might achieve this with convenience init something like this:

convenience init(foo: String?) {
    self.init()
    self.customSetup()
}

Is there any way to create custom init without parameters?

like image 695
Evgeniy Kleban Avatar asked May 11 '18 09:05

Evgeniy Kleban


1 Answers

You need to create a static method:

static func initWithSomeMode() -> YourClass {
    let obj = YourClass()
    obj.someCustomSetup()
    return obj
}

And then you can do this:

let yourClass = YourClass.initWithSomeMode()
like image 61
Sweeper Avatar answered Nov 08 '22 15:11

Sweeper