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. So you can use an optional to represent the spouse name. Let's see how this works:
- Type in and run the following code:
// optionalsvar spouseName: Stringprint(spouseName)
Since Swift is type-safe, it will display an error, Variable 'spouseName' used before being initialized.
- You could assign an empty string to spouseName as follows. Modify your code as shown:
// optionalsvar spouseName: String = ""print(spouseName)
This makes the error go away, but an empty string is still a value, and we don't want spouseName to have a value.
In cases like ...