Implicitly Unwrapped Optionals
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
var username: String! = "swiftdev"
print("Username: \(username)")
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
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")
Login to try C/C++/Java/PHP code in the editor
- 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.
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: