UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Why would you want a failable initializer?

Paul Hudson    @twostraws   

Updated for Xcode 15

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:

  1. Write your initializer as init?() rather than init()
  2. Return nil for any paths that should fail

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.

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.