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. So you can use an optional to represent the spouse name. Let's see how this works:

  1. 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.

  1. 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 ...

Get iOS 13 Programming for Beginners - Fourth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.