Introducing optionals
Up until now, every time you declared a variable or constant, you assigned a value to it immediately. But what if you want to declare a variable first and assign a value later? In this case, you would use optionals.
Important information
For more information on optionals, visit https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html.
Let's now learn how to create and use optionals, and see how they are used in a program.
Using optionals and optional binding
Imagine you're writing a program where the user needs to enter the name of their spouse. Of course, if the user is not married, there would be no value for this. In this case, you can use an optional to represent the spouse's name. Follow these steps:
- Add the following code to your playground to create a variable and print its contents. Click the Play/Stop button to run it:
var spouseName: String print(spouseName)
Since Swift is type-safe, it will display an error...