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