Morpheu5
Morpheu5

Reputation: 2801

On declaring optionals and non-optionals in Swift

I'm confident this might be a duplicate, but I can't find any tidy and compact explanation, so here it goes.

We all know that, if we declare a variable like this

1> var a : String?

we get an optional

a: String? = nil

and if we omit the ? we have to initialize a to something else than nil at creation time. However, if we say something like

2> var a : String!

we get

a: String! = nil

which confuses me to no ends, because I was under the assumption that that declaration meant that a could not be an optional. So, playing around with the REPL, I get the following bemusing results:

 3> a!
fatal error: unexpectedly found nil while unwrapping an Optional value

 4> a as! String
fatal error: unexpectedly found nil while unwrapping an Optional value

 5> a as! String?
$R2: String? = nil

 6> a as? String
fatal error: unexpectedly found nil while unwrapping an Optional value

 7> a as? String!
$R3: String!? = nil

Can someone provide some light into this?

Upvotes: 0

Views: 81

Answers (1)

hannad
hannad

Reputation: 822

var a: String! is what we call an implicitly unwrapped optional. It is an optional that may hold the value of nil, but the compiler does not produce any compile-time errors regarding it.

If it had a nil value, and was used, you will get a runtime error as if you would by force unwrapping a normal optional that has a nil value.

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.

Upvotes: 3

Related Questions