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.
Syntax
var name: Type! = value // implicitly unwrapped
name.member // used without ! or ?
name = nil // accessing it now crashes
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
// Declare a mutable variable `username` (a `String!`), initialized to `"swiftdev"`
var username: String! = "swiftdev"
// Print "Username: \(username)" to the console
print("Username: \(username)")
// Print `username.uppercased()` to the console
print(username.uppercased())
Login to try C/C++/Java/PHP code in the editor
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
// Declare a mutable variable `configValue` (a `Int!`), initialized to `100`
var configValue: Int! = 100
// Check whether `configValue != nil`
if configValue != nil {
// Print "Config is set to \(configValue!)" to the console
print("Config is set to \(configValue!)")
}
configValue = nil
// Print "Config is now nil, checking before use avoids a crash" to the console
print("Config is now nil, checking before use avoids a crash")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- 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. - Forgetting that an implicitly unwrapped optional still crashes at runtime, just like force-unwrapping, if it's accessed while actually
nil. - Not realizing
Type!can still be checked withif letor compared toniljust 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: