O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Failable Initializers

Sometimes it is useful to define a type whose initialization can fail. In these cases, you need a way to report to the caller that you were not able to initialize the instance. You use failable initializers to handle these scenarios.

There are a number of reasons why you might want initialization to fail. A type’s initializer may be given invalid parameters. For example, you might want to have an initializer fail if someone tries to initialize an instance of Town with a negative population. Or perhaps a type’s initialization depends on an external resource that is not available, as in let image = UIImage(named: "nonexisting-image"). This code would fail to create a UIImage instance because the image resource does ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required