Why bother implicitly unwrapped optional?

If we don’t want unnecessary if-let statements, can we just use regular type?

The answer lies below.

The swift programming language guide says:

Optionals

You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.

Except for the way it is unwrapped, an implicitly unwrapped optional is just like a regular optional. But once after being set a value, it should not be set to nil again.

Again the swift programming language guide says:

Sometimes it’s clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it’s useful to remove the need to check and unwrap the optional’s value every time it’s accessed, because it can be safely assumed to have a value all of the time.

These kinds of optionals are defined as implicitly unwrapped optionals . You write an implicitly unwrapped optional by placing an exclamation mark ( String! ) rather than a question mark ( String? ) after the type that you want to make optional.

Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization, as described in Unowned References and Implicitly Unwrapped Optional Properties.

NOTE

Don’t use an implicitly unwrapped optional when there’s a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.

I hope this makes sense, but better to consult the language guide when something feels fuzzy.

Learn Coding with Pretty Function

1 Like