Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Failable Initializers in Swift
Written by Team Kodeco

In Swift, initializers can be marked as failable, meaning they can return an optional value of the type they are initializing. This allows you to create objects that may not be able to be fully initialized in certain circumstances.

A failable initializer will return an optional value of the instance type and can be called with the init? syntax.

struct Person {
  let name: String
  let age: Int
  
  init?(name: String, age: Int) {
    if age < 0 {
      return nil
    }
    self.name = name
    self.age = age
  }
}

Here, the Person struct has a failable initializer that initializes the properties of the struct. It checks if the age is less than 0, if it is, returns nil otherwise it initializes the properties.

let goodPerson = Person(name: "John", age: 25) // Person(name: "John", age: 25)
let badPerson = Person(name: "John", age: -1) // nil

In this example, goodPerson is able to be initialized and is of type Person, while badPerson is nil because the age is negative.

When working with failable initializers, it’s important to keep in mind that you’ll need to handle the case where the initializer returns nil in your code. One way to do this is by using optional binding with if let or guard let statements:

if let person = Person(name: "John", age: 25) {
  print(person.name)
} else {
  print("Error creating person")
}

This code creates a Person instance and uses optional binding to check if the instance was created successfully. If it was created successfully, it prints the name of the person, otherwise it prints “Error creating person”.

© 2024 Kodeco Inc.