Snowman
Snowman

Reputation: 32061

Why is the ! in Swift called an 'implicitly' rather than 'explicitly' unwrapped optional?

The name of the ! always confuses me: it's called an 'implicitly unwrapped optional'. However, what is implicit about it? Implicit means "implied though not plainly expressed." However, does not adding a ! plainly express its purpose? Does not adding a ! make it explicit what we are trying to accomplish?

Upvotes: 22

Views: 6135

Answers (2)

drewag
drewag

Reputation: 94683

In Swift, trailing exclamation marks (!) are used in two different ways. One is called Forced Unwrapping. This is when you have a variable defined as an Optional and you want to basically assert that the value is not nil so that you can use it as if it were not an optional:

var optionalName: String? = "World"
if optionalName != nil {
    sayHelloTo(optionalString!)
}

An alternate way you could describe "Forced Unwrapping" is "Explicit Unwrapping", but forced adds the extra hint that the whole program will crash if you try to "Force Unwrap" an optional that is nil.

The second is when you are actually declaring the type of a variable and it is called an Implicitly Unwrapped Optional. This is for when you want to declare a variable that is technically optional, but that you will treat as if it is not optional. Every time you use this Implicitly Unwrapped Optional, it is in reality, doing the "Force Unwrapping" I described above:

var name: String! = "World"
if name != nil {
    sayHelloTo(name)
}

You can still test an Implicitly Unwrapped Optional for nil, but you can also use it directly as if it were not optional. That is why it is considered implicit. Every time you use it, it is automatically, implicitly unwrapped for you.

Like "Forced Unwrapping" an "Implicitly Unwrapped Optional" will still crash the entire program if you try to use it when it is nil

Upvotes: 30

Bryan Chen
Bryan Chen

Reputation: 46578

Normal Optional

var foo : Foo? = Foo()
foo!.doSomething() // explicitly unwrap it and call the method

Implicitly Unwrapped Optional

var foo : Foo! = Foo()
foo.doSomething() // implicitly unwrap it and call the method just like it is not optional

In both case, you need something to declare an optional (? or !). Implicitly Unwrapped Optional does not add more. But you can omit unwrap operator when use it.

Upvotes: 7

Related Questions