SLN
SLN

Reputation: 5092

Why there is no optional(nil) but only nil?

Given the follwoing code example:

var ResponseCode: Int? = 404
print(ResponseCode) // --> Optional(404)
ResponseCode = nil
print(ResponseCode) // --> nil (why not Optional(nil)?)

Question: why when I printed a nil-valued option it is just a nil. Why not also showing the Optional(nil)

Thanks for your time and help.

Upvotes: 3

Views: 88

Answers (2)

Sulthan
Sulthan

Reputation: 130191

This is rather simple to explain. Optional is an enum that has two values: .Some(T) and .None.

As you see, only one of them has a parameter.

The string description of .Some(T) is "Optional(description of T)". .None has no parameters so the description is just nil.

Note you can sometimes see "Optional(nil)" in your log, however, in that case we are dealing with double optionals (e.g. Int??).

print(Optional<Int?>(Optional<Int>.None)) // prints "Optional(nil)"

Upvotes: 3

Alexander
Alexander

Reputation: 63403

Because nil is a constant literal meaning Option.None.

Allowing an Optional to store a nil value wouldn't make sense, and would completely defeat the purpose (enforcement of non-nullability) of Optionals.

Upvotes: 3

Related Questions