Reputation: 5092
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
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
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