Are nil and Optional<T>.None the same thing in Swift?

null, swift

Solution

If you don’t provide an initial value when you declare an optional variable or property, its value automatically defaults to nil.

They have same value, both are `nil`.

Actually `Optional<T>.None` is a polymorphic primitive value, and `nil` is a constant having this value. `Optional<T>` is a polymorphic type. The type of `nil` is `Optional<T>`. That's why you cannot assign `nil` to anything else but an `Optional<T>`. For the same reason you cannot assign `true` to anything but a `Bool`.

For now, according to the documentation you can not use `nil` for any custom and arbitrary type but optionals.

nil cannot be used with non-optional constants and variables. If a constant or variable in your code needs to be able to cope with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type.

Problem

I'm a bit confused by Swift tutorials. Is `nil` just a convenient shortcut for `Optional<T>.None`? Is there an implicit conversion from one to another? A couple of observations: - `Optional<String>.None == nil` - `nil` literal seems to have a `NilType` If this is an implicit conversion, can I define my own type that “accepts” nil, or is `Optional` somehow special in this regard? I don't think defining custom convertible-to-nil types is a good idea—I'm just trying to understand how the type system works in this case.

Original source