O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Modifying an Optional in Place

You can modify an optional in place so that you do not have to create a new variable or constant. Add a call to the append(_:) method on upCaseErrorDescription.

Listing 8.10 Modifying in place

...
upCaseErrorDescription?.append(" PLEASE TRY AGAIN.")
upCaseErrorDescription

Modifying an optional in place can be extremely helpful. In this case, all you wanted to do was update a string inside of an optional. You did not need anything returned. If there was a value inside of the optional, then you wanted to add some text to the string. If there was no value, then you did not want to do anything.

This is exactly what modifying an optional in place does. The ? at the end of upCaseErrorDescription ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required