Book Image

Learning Swift

By : Andrew J Wagner
Book Image

Learning Swift

By: Andrew J Wagner

Overview of this book

Table of Contents (18 chapters)
Learning Swift
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Optional chaining


A common scenario in Swift is to have an optional that you must calculate something from. If the optional has a value you want to store the result of the calculation on, but if it is nil, the result should just be set to nil:

var invitee: String? = "Sarah"
var uppercaseInvitee: String?
if let actualInvitee = invitee {
    uppercaseInvitee = actualInvitee.uppercaseString
}

This is pretty verbose. To shorten this up in an unsafe way, we could use forced unwrapping:

uppercaseInvitee = invitee!.uppercaseString

However, optional chaining will allow us to do this safely. Essentially, it allows optional operations on an optional. When the operation is called, if the optional is nil, it immediately returns nil; otherwise, it returns the result of performing the operation on the value within the optional:

uppercaseInvitee = invitee?.uppercaseString

So in this call, invitee is an optional. Instead of unwrapping it, we will use optional chaining by placing a question mark (?) after it,...