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: "non-existing-image").
This code would fail to create a UIImage instance because the image resource ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access