Failable Initializer in Swift

Gabriel Theodoropoulos
3 min readMay 13, 2021

As developers, we use initializers all the time to create instances of various types. We also create our own initializers when implementing custom classes or structs. But should initializers always return an instantiated object of the type they are implemented into?

It makes sense sometimes not to return an object if the initialization of one or more properties that play crucial role in the type does not succeed. A failable initializer in Swift is an initializer that allows to do that, as it can potentially return nil if one or more conditions are not satisfied.

A hands-on example

Let’s see an example to demonstrate that. Suppose that we are implementing a custom class that applies various filters to images. In order to do so, we need an image property first:

class FilteredImage {
var image: UIImage?
}

For flexibility reasons, let’s also suppose that we can initialize an instance of the above class in two ways; either by providing an actual image object, or an image name. For the former case, such an initializer is pretty simple:

class FilteredImage {
var image: UIImage?

init(with image: UIImage) {
self.image = image
}
}

In case of providing the image name only, things need some additional…

--

--

Gabriel Theodoropoulos
Gabriel Theodoropoulos

Written by Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev