UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Optional vs implicitly unwrapped optional: what’s the difference?

Swift version: 5.6

Paul Hudson    @twostraws   

When you’re just learning Swift, the difference between an optional (String?), an implicitly unwrapped optional (String!), and a regular type (String) can seem awfully confusing. Here’s a quick summary that should explain the difference:

When you use String you’re saying this will always have a string inside, and can never have nothing inside. It might be an empty string (""), but even an empty string is still a string.

When you use String? you’re saying this might have a string inside, but it might have nothing at all inside – not even an empty string. Swift won’t let you use these without unwrapping them, which is usually done using if let.

When you use String! you’re saying this might have a string inside, but it might have nothing at all inside – not even an empty string. However, Swift lets you use these as if they were a String, as if they always do have a value, but if you try to use a nil value by accident your code will crash. This effectively lets you say “I know this might be nil, but I’m so sure it has a value that I’m willing for my program to crash if I’m wrong.”

So: String is definitely a string, String? might be nil or might be a string, and String! might be nil but when you use it you’re absolutely sure it has a string.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 8.0

Similar solutions…

About the Swift Knowledge Base

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

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.2/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.