Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

null

swift

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.

like image 370
Dan Abramov Avatar asked Jun 05 '14 10:06

Dan Abramov


People also ask

What is the difference between optional none and nil?

Question : What's the difference optional between nil and . None? Answer : There is no difference.

What is optional in Swift and nil in Swift?

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).

What does nil mean Swift?

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.

What is none in Swift?

The absence of a value.


1 Answers

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.

like image 133
masoud Avatar answered Oct 14 '22 20:10

masoud