Chapter 9. Optionals
In Swift, it is illegal to use a variable before you have given it a value. And once a value has been set, it is impossible to take the value away; you can only assign another value of the same type. But sometimes you need to represent the absence of a value, or a value that might go away, without crashing your app.
If you ask someone “How many beans are in this jar?”, you might expect an integer answer (and declare an Int
variable to store it).
But if they answer “I don’t know,” what should you put in your variable? 0
? Some other number?
If your variable can only store values of type Int
,
what do you do so that you can move on with your program and deal with the lack of an answer later?
You need a way to declare a variable ...
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.