null / nil in swift language
IosSwiftIos Problem Overview
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. Thanks in advance.
Ios Solutions
Solution 1 - Ios
Regarding equivalents:
NULL
has no equivalent in Swift.nil
is also callednil
in SwiftNil
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.
Solution 2 - Ios
If you need to use a NULL at low level pointer operations, use the following:
UnsafePointer<Int8>.null()
Solution 3 - Ios
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.
Solution 4 - Ios
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 asNSNull()
Solution 5 - Ios
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
Solution 6 - Ios
if !(myDATA is NSNull) {
// optional is NOT NULL, neither NIL nor NSNull
} else {
// null
}