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 ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.