Mehul Parmar
Mehul Parmar

Reputation: 3699

null / nil in Swift

How do you define the following in Swift:

In other words, what would be the Swift equivalent of each of these Objective-C terms?

I would also like to know whether any specific use cases exist for non-Objective-C types like structs and enums.

Upvotes: 87

Views: 112228

Answers (6)

ChandreshKanetiya
ChandreshKanetiya

Reputation: 2414

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

Upvotes: 8

Yakup Ad
Yakup Ad

Reputation: 1651

if !(myDATA is NSNull) {
// optional is NOT NULL, neither NIL nor NSNull
} else {
// null
}

Upvotes: 0

Rien
Rien

Reputation: 658

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

UnsafePointer<Int8>.null()

Upvotes: 23

Ciprian
Ciprian

Reputation: 1205

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

Upvotes: 5

Tommy
Tommy

Reputation: 100612

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.

Upvotes: 13

gwcoffey
gwcoffey

Reputation: 5921

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.

Upvotes: 134

Related Questions