Failable Initializer in Swift

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?
}
class FilteredImage {
var image: UIImage?

init(with image: UIImage) {
self.image = image
}
}
let image = UIImage(named: imageName)
  1. Initializer must contain at least one path of code execution that returns nil.
class FilteredImage {
...

init?(with imageName: String) {
guard let image = UIImage(named: imageName) else {
return nil
}
self.image = image
}
}
let filteredImage = FilteredImage(with: "bird")
guard let filteredImage = FilteredImage(with: "bird") else {
// filteredImage is nil
return
}

// filteredImage is initialized and we use it normally

Summary

That’s the failable initializer in Swift; a handy tool in order to return nil objects in case the desired initialization fails. Have you been using it already? Are you planning to do so? No matter what, I hope there is something new for you in this post that will improve your daily development workflow. Thank you for reading!

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store