Failable Initializer Explained in Swift
For times when you need to initialize an object whose stored properties may or may not have values during initialization, a failable initializer is your secret weapon.
A failable initializer creates an optional instance of the object by placing a question mark or an exclamation mark after the init keyword.
Here’s how it works.
class User {
let name: String
init?(name: String) {
if !name.isEmpty {
self.name = name
return
}
return nil
}
}
var myUser = User(name: "Ijeoma")
print(myUser!.name.uppercased()) // output: IJEOMA
Here, the User class has a stored property of type String.
Then, a failable initializer is declared—the init keyword followed by a question mark—and an if-statement is used in the body of the initializer method to check whether the parameter is not empty.
领英推荐
If the check returns true, the method’s parameter is assigned to the stored property and the return keyword is used to exit the if-statement.
Otherwise, the failable initializer returns nil.
It’s important to note that when an initializer doesn’t accomplish the initialization process and needs to return nil, explicitly return nil. The keyword ‘nil’ is the only return value permitted in an initializer, therefore, an implicit return will not work.
Next, the User object is initialized with the value “Ijeoma” and the result is an Optional that’s assigned to the variable myUser.
Finally, we unwrap the Optional instance (with !) so that we can use it as a regular variable — in this case, turn the letters into all caps using the uppercased() method.
We could have also written this code with a failable initializer that creates an implicitly unwrapped optional instance by adding an exclamation mark after the init keyword, like this: init!(…).