O'Reilly logo

iOS Programming: The Big Nerd Ranch Guide, 6th Edition by Aaron Hillegass, Christian Keur

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

Error Handling

It is often useful to have a way of representing the possibility of failure when creating methods. You have seen one way of representing failure throughout this book with the use of optionals. Optionals provide a simple way to represent failure when you do not care about the reason for failure. Consider the creation of an Int from a String.

let theMeaningOfLife = "42"
let numberFromString = Int(theMeaningOfLife)

This initializer on Int takes a String parameter and returns an optional Int (an Int?). This is because the string may not be able to be represented as an Int. The code above will successfully create an Int, but the following code will not:

let pi = "Apple Pie"
let numberFromString = Int(pi)

The string ...

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