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.
Question : What's the difference optional between nil and . None? Answer : There is no difference.
However there is another data type in Swift called Optional, whose default value is a null value ( nil ). You can use optional when you want a variable or constant contain no value in it. An optional type may contain a value or absent a value (a null value).
In Swift, nil means the absence of a value. Sending a message to nil results in a fatal error. An optional encapsulates this concept. An optional either has a value or it doesn't. Optionals add safety to the language.
The absence of a value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With