ImplicitlyUnwrappedOptional type in Swift

Shashank Mishra
Mac O’Clock
Published in
2 min readMay 10, 2020

Before Swift 4.0, we use “!” while declaring a variable in order to get the unwrapped optional value (while using it). As per SE-0054, ImplicitlyUnwrappedOptional<T> is no longer a distinct type; there is only Optional<T> now.

Let's start our discussion from the new change that we have seen after updating Swift to 4.0.

Note: In the above example we are getting Optional(“Shashank”) but what we are expecting? Correct! unwrapped value i.e. “Shashank”. It was before Swift 4.0

What has been changed from Swift 4.0

The appearance of “!” at the end of a property or variable declaration’s type no longer indicates that the declaration has IUO(implicitly unwrapped optional) type. It indicates that

#1 It has an optional type

#2 It has an attribute indicating that its value may be implicitly forced.

Now “!” will be treated as an optional type with one ad-on. That means, can also be automatically unwrapped when used in any assignment or expression depending on the type checker.

If we use the same “name” variable with an expression, the compiler will force the optional. See the example —

See one more example —

Conclusion

IUO(“!”) while declaring the variable will be treated an optional only and it needs additional wrapping while printing it.

If you use it in any expression, depending on type-checker, it will automatically give unwrapped value.

Note — Except for a few specific scenarios, optionals are always the safer bet, and we’d like to encourage people to use them instead of IUOs.

--

--