jjaeko
jjaeko

Reputation: 235

Why use force unwrapping in this example?

let john = Person()
john.residence = Residence()

let johnsAddress = Address()
johnsAddress.buildingName = "The Larches"
johnsAddress.street = "Laurel Street"

john.residence!.address = johnsAddress

The above example is in Apple Language Guide.

Why did you use force unwrapping (exclamation mark) in the last line?

Is there a difference between ! and ? in this example?

Upvotes: 3

Views: 872

Answers (1)

Antonio
Antonio

Reputation: 72790

A forced unwrapping is used when it's know that the optional has a non nil value. Using it on an optional with nil value generates a runtime exception.

The normal unwrapping instead is conditional. If john.residence is nil, then whatever is after it is ignored, and no error is generated (see Optional Chaining). The statement simply doesn't do anything, hence no assignment takes place.

The reason why the forced unwrapping exists is that it avoids checking for nils when it's known it has a value. For instance let's suppose you want to print to the console the content of a String variable:

let x: String?
print("\(x)")

If you initialize the variable instead, it will print something you wouldn't probably expect:

let x: String? = "Test"
print("\(x)") // Prints "Optional("Test")"

That happens because x is an Optional and not a String type. To fix that, you force the unwrapping using the exclamation mark:

print("\(x!)") // Prints "Test"

Upvotes: 9

Related Questions