null / nil in swift language null / nil in swift language ios ios

null / nil in swift language


Regarding equivalents:

  • NULL has no equivalent in Swift.
  • nil is also called nil in Swift
  • Nil has no equivalent in Swift
  • [NSNull null] can be accessed in Swift as NSNull()

Note: These are my guesses based on reading and play. Corrections welcome.

But nil/NULL handling in Swift is very different from Objective C. It looks designed to enforce safety and care. Read up on optionals in the manual. Generally speaking a variable can't be NULL at all and when you need to represent the "absence of a value" you do so declaratively.


If you need to use a NULL at low level pointer operations, use the following:

UnsafePointer<Int8>.null()


nil means "no value" but is completely distinct in every other sense from Objective-C's nil.

It is assignable only to optional variables. It works with both literals and structs (i.e. it works with stack-based items, not just heap-based items).

Non-optional variables cannot be assigned nil even if they're classes (i.e. they live on the heap).

So it's explicitly not a NULL pointer and not similar to one. It shares the name because it is intended to be used for the same semantic reason.