Failable Initializers

Sometimes it is useful to define a type whose initialization can fail at runtime. For example, imagine defining a struct to model a combination lock, such as what someone might put on their luggage. You would want to ensure that every new instance was initialized with a four-digit integer combination, 0000 through 9999, as its argument.

Checking that the passed-in combination is valid must happen when the program is running. What should the initializer do if the combination is invalid? One solution is to return nil from the initialization process.

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.

A failable ...

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition 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.