Swift Tips: Failable init

Tuğçe Arar
Nov 3, 2022
by Pixpedia

Initializers might work or might not. For the case of not working, we can return nil.

We write a failable initializer by placing a question mark after the init keyword (init?)

init?()

init!()

It solves the confusion between Factory methods and initializers.

We can’t create an failable and non failable initializers with the same name and parameter.

Initializers normally don’t return a value but we can add a fail state by returning nil.

if let myButton = MyButton(buttonType: .default) {
// init the button successfully
} else {
// could not init the button
}

Enumeration with raw values have failable init by default.

enum ButtonTypes: Int {
case default
case primary
case secondary
case informative
}
let buttonType = ButtonTypes(rawValue: 2)

We can override failable init of superclass. In fact we can override failable init into non failable init.

--

--