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:
// optionals
var spouseName: String
print(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:
// optionals
var 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 these, we can use optionals. An optional may have one of two possible states. Either it does not contain a value, or it contains a value, and you can access the value by a process called unwrapping.

  1. To make spouseName an optional, type a question mark after the type annotation and run your program:
// optionals
var spouseName: String?
print(spouseName)

Even though there is a warning, the program will execute. Ignore the warning for now:

The value of spouseName is shown as "nil " in the Results area, and nil is printed in the Debug area. nil is a special keyword that means the optional has no value.

  1. Let's assign a value to spouseName. Modify the code as shown:
// optionals
var spouseName: String?
spouseName = "Lydia"

print(spouseName)

When you run this, you would expect Lydia to appear in the Debug area. Instead, Optional("Lydia") is printed, showing that the optional has not been unwrapped.

  1. Add one more line of code as follows:
// optionals
var spouseName: String?
spouseName = "Lydia"
print(spouseName)
let greeting = "Hello, " + spouseName

You'll get an error, and the Debug area shows you where the error occurred.

This happened because you can't use an optional's value without unwrapping it first.

  1. Click on the red circle to display possible fixes, and you'll see the following:

  1. Click the second fix, and you'll see an exclamation mark appear after spouseName in the last line of code. The program runs fine now, and the value of greeting is Hello, Lydia as shown in the Results area. Force-unwrapping unwraps an optional whether it contains a value or not. It works fine if spouseName has a value, but if spouseName is nil, your program will crash.
  1. To see this, modify your program as shown and run it:
// optionals
var spouseName: String?
spouseName = nil
print(spouseName)
let greeting = "Hello, " + spouseName!

Your program crashes, and you can see what caused the crash in the Debug area:

Since spouseName is now nil, the program crashed while attempting to force-unwrap spouseName.

A better way of handling this is to use optional binding. In optional binding, we attempt to assign the value in an optional to a temporary variable (we can name it whatever we like). If the assignment is successful, a block of code is executed.

  1. Modify your program as follows and run it:
// optionals
var spouseName: String?
spouseName = "Lydia"
print(spouseName)
// optional binding
if let spouse = spouseName {
let greeting = "Hello, " + spouse
print(greeting)
}

Here's how it works. If spouseName has a value, it will be unwrapped and assigned to spouse, and the if statement will return true. The statements between the curly braces will be executed and the constant greeting will then be assigned to the value "Hello, Lydia". Then, Hello, Lydia will be printed in the Debug area. Note that spouse is not an optional.

If spouseName does not have a value, no value can be assigned to spouse and the if statement will return false. In this case, the statements in the curly braces will not be executed at all.

  1.  Modify your program as follows and run it:
// optionals
var spouseName: String?
spouseName = nil
print(spouseName)
if let spouse = spouseName {
let greeting = "Hello, " + spouse
print(greeting)
}

You'll notice that nothing appears in the Debug area, and your program no longer crashes even though spouseName is nil.

This concludes the section on optionals and optional binding. Awesome!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.98.108