← Back to Swift Course | Chapter 5: Optionals | Lesson 8 of 8

Implicitly Unwrapped Optionals

An implicitly unwrapped optional is a value that's technically an optional box, but Swift lets you use it directly without opening it every time, trusting it will have something inside after setup.

Declaring an Implicitly Unwrapped Optional

An implicitly unwrapped optional is declared with ! instead of ?, allowing its value to be used directly without manual unwrapping each time, once it has been assigned.

Example: Declaring an Implicitly Unwrapped Optional

markup
var username: String! = "swiftdev"
print("Username: \(username)")
print(username.uppercased())

Still Crashes When nil

Even though it can be used directly, an implicitly unwrapped optional still crashes the program if it's accessed while holding nil, so it should only be used when a value is guaranteed.

Note: Treat Type! with the same caution as force-unwrapping -- only use it when a nil value would indicate a genuine programming error.

Example: Still Crashes When nil

markup
var configValue: Int! = 100
if configValue != nil {
    print("Config is set to \(configValue!)")
}
configValue = nil
print("Config is now nil, checking before use avoids a crash")
Common Mistakes
  1. Using String! as a general substitute for regular optionals; it should be reserved for cases where a value starts nil but is guaranteed to be set before use.
  2. Forgetting that an implicitly unwrapped optional still crashes at runtime, just like force-unwrapping, if it's accessed while actually nil.
  3. Not realizing Type! can still be checked with if let or compared to nil just like a normal optional -- it isn't a completely different mechanism.
Chapter Summary
  • Type! declares an implicitly unwrapped optional, usable directly without ! at each access.
  • It still crashes at runtime if accessed while nil, just like a forced unwrap.
  • It's mainly used for values guaranteed to be set immediately after declaration, before first use.
  • It can still be treated as a regular optional when needed, e.g. with if let.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.