Updated for Xcode 14.2
If an initializer for a struct or class can fail – if you realize part-way through that you cannot create the object using the data you were provided – then you need a failable initializer. Rather than returning a new object instance, this returns an optional instance that will be nil if initialization failed.
Making a failable initializer takes two steps:
init?()
rather than init()
You can have as many failing paths as you need, but you don’t need to worry about the success path – if you don’t return nil from the method, Swift assumes you mean everything worked correctly.
To demonstrate this, here’s an Employee
struct that has a failable initializer with two checks:
struct Employee {
var username: String
var password: String
init?(username: String, password: String) {
guard password.count >= 8 else { return nil }
guard password.lowercased() != "password" else { return nil }
self.username = username
self.password = password
}
}
That requires passwords be at least 8 characters and not be the string “password”. We can try that out with two example employees:
let tim = Employee(username: "TimC", password: "app1e")
let craig = Employee(username: "CraigF", password: "ha1rf0rce0ne")
The first of those will be an optional set to nil because the password is too short, but the second will be an optional set to a valid User
instance.
Failable initializers give us the opportunity to back out of an object’s creation if validation checks fail. In the previous case that was a password that was too short, but you could also check whether the username was taken already, whether the password was the same as the username, and so on.
Yes, you could absolutely put these checks into a separate method, but it’s much safer to put them into the initializer – it’s too easy to forget to call the other method, and there’s no point leaving that hole open.
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.