Zero and Optional <T>. Not the same in Swift?
I am a little confused by Swift tutorials.
Is nil just a handy shortcut for Optional<T>.None ?
Is there an implicit conversion from one to another?
A few observations:
Optional<String>.None == nilnilliteral hasNilType
If this is an implicit conversion, can I define my own type that "takes" zero or is Optional something special in this regard? I donโt think that defining custom types convertible to zero is a good idea. I'm just trying to understand how the type system works in this case.
If you did not specify an initial value when you declare an optional variable or property, its value is automatically set to zero by default.
They have the same value, both nil values.
In fact, Optional<T>.None is a polymorphic primitive value, and nil is a constant that has this value. Optional<T> is a polymorphic type. Type nil - Optional<T> . This is why you cannot assign nil to anything other than Optional<T> . For the same reason, you cannot set true to anything other than Bool .
Currently, according to the documentation, you cannot use nil for any custom and custom type except options.
nil cannot be used with optional constants and variables. If a constant or variable in your code should be able to cope with the lack of a value under certain conditions, always declare it as an optional value of the appropriate type.