Search code examples
swiftnulloption-type

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.


Solution

  • 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)"