Implicitly Unwrapped Optional in Swift

If the optional variable(or constant) will always have a value but not nil then we can unwrap the optional during its declaration itself by using ! instead of ? after the type. This will avoid unnecessary checks and unwrapping of optional value each time it is accessed.

We can still use implicitly unwrapped optional to check whether it has a value using if statement and can also use optional binding to extract its value.

Implicitly Unwrapped Optional must always have a non-nil value during declaration and any point of time after that. If it has a nil value at any point of time, runtime error will occur.

Leave a Reply