NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

Why would you want a failable initializer?

Paul Hudson    @twostraws   

Updated for Xcode 13.3

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 Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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

Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.