Why use a force sweep 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 the Apple Language Guide.

Why did you use the force sweep (exclamation mark) on the last line?

Is there any difference between !

and ?

in this example?

+3


source to share


1 answer


Forced unfolding is used when an option is known to have a value other than zero. Using this parameter with the optional nil value throws an exception at runtime.

The normal sweep is, instead, conditional. If john.residence

- nil

, then everything after it is ignored and no error is generated (see Optional chaining ). The assertion simply does nothing, hence no assignment occurs.

The reason forced unwrapping exists is because it avoids checking for nils when it knows it matters. For example, suppose you want to print the contents of a variable to the console String

:

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

      



If you initialize a variable instead, it prints out what you probably don't expect:

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

      

This is because it x

is Optional

, not a type String

. To fix this, you force expand using an exclamation mark:

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

      

+9


source







All Articles