NEW! Pre-order my latest book, Testing Swift! >>

How to unwrap an optional in Swift

Paul Hudson       @twostraws

Optional values are a central concept in Swift, although admittedly they can be a little hard to understand at first. Put simply, an optional value is one that may or may not exist, which means Swift won't let you use it by accident – you need to either check whether it has a value and unwrap it, or force unwrap. Of the two options the first is definitely preferable, because it's significantly safer.

To check whether an optional has a value then unwrap it all in one, you should use if let syntax, like this:

// fetch an example optional string
let optionalString = fetchOptionalString()

// now unwrap it
if let unwrapped = optionalString {
    print(unwrapped)
}

In that example, the print(unwrapped) line will only be executed if optionalString has a value. If that line is reached, you can know for sure that unwrapped has a value that you can use, which makes that code safe.

Available from iOS 7.0 – see Hacking with Swift tutorial 1

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Want to build macOS apps?

Hacking with macOS delivers 18 awesome projects that teach you macOS development in no time – take control of your desktop today!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>