April 2020
Intermediate to advanced
528 pages
15h 40m
English
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 ...
Read now
Unlock full access