Implicitly Unwrapped Optionals in Swift
Written by Team Kodeco
An implicitly unwrapped optional is similar to a regular optional, but is automatically unwrapped when accessed. This means that you can access the value of an implicitly unwrapped optional without having to check if it’s nil
first. However, if the implicitly unwrapped optional is nil
and you try to access its value, a runtime error will occur.
To declare an implicitly unwrapped optional, you can add an exclamation mark (!
) after the type. For example, var age: Int!
declares an implicitly unwrapped optional integer.
Here is an example of using an implicitly unwrapped optional:
var age: Int! = nil
age += 1 // runtime error: unexpectedly found nil while unwrapping an Optional value
It’s important to note that implicitly unwrapped optionals should only be used when you are certain that the value will not be nil
after the initial assignment. If there’s a possibility that the value may become nil
, you should use a regular optional instead.