82

How would we define the following in swift programming language :

  • null
  • nil
  • Nil
  • [NSNull null]

In other words, what would be the swift equivalent of each of these objective c terms. Besides, would also like to know whether any specific use cases exist for non objective c types like structs and enums.

starball
  • 20,030
  • 7
  • 43
  • 238
Mehul Parmar
  • 3,599
  • 3
  • 26
  • 42

6 Answers6

130

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.

gwcoffey
  • 5,551
  • 1
  • 18
  • 20
22

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

UnsafePointer<Int8>.null()
Pang
  • 9,564
  • 146
  • 81
  • 122
Rien
  • 638
  • 6
  • 10
13

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.

Tommy
  • 99,986
  • 12
  • 185
  • 204
8

Swift’s nil is not the same as nil in Objective-C.
In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.

  • 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()

pkamb
  • 33,281
  • 23
  • 160
  • 191
ChandreshKanetiya
  • 2,414
  • 5
  • 27
  • 41
5

The concept of Null in Swift resumes to the Optional enum. The enum is defined like this

enum Optional<T> {
  case Some(T)
  case None
}

What this means is that you cannot have an uninitialised variable/constant in Swift.. If you try to do this, you will get a compiler error saying that the variable/constant cannot be uninitialised. You will need to wrap it in the Optional enum..

This is the only Null concept you will find in Swift

Ciprian
  • 1,125
  • 1
  • 9
  • 14
0
if !(myDATA is NSNull) {
// optional is NOT NULL, neither NIL nor NSNull
} else {
// null
}
Yakup Ad
  • 1,591
  • 16
  • 13