Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between nil and () in Swift

Tags:

null

swift

tuples

I noticed that the empty tuple () is used to represent an absence of value in Swift. For example, the signature of a function that returns nothing, is:

func zz(){
    println("zz")
}

The compiler will also accept this body for the function above:

func zz(){
    println("zap")
    return ()   // returning () and returning nothing is the same thing!
}

An equivalent way of defining this function would be:

func zz() -> (){
    println("zap")
    return ()
}

There's even a typealias for () called Void:

typealias Void = ()

So if the empty tuple is the absence of value in Swift, what is its relationship with nil? Why do we need both concepts? is nil defend in terms of ()?

like image 378
cfischer Avatar asked Jan 09 '23 15:01

cfischer


2 Answers

nil is a special value that you can assign to an Optional to mean the optional doesn't have a value. nil is not really the absence of a value, it's a special value that means no proper value

() means that nothing is returned (or passed in), not even an optional. There is no return value, nor can there ever be. You can't assign it to anything unlike a return value of nil.

The situation is analogous to the difference between (in C)

void foo(void);

and

SomeType* bar(void);

if the latter function uses a return value of NULL to indicate some sort of failure. i.e.

someVariable = foo();   // Illegal

someVariable = bar();   // Not illegal
if (someVariable != NULL) { ... }
like image 96
JeremyP Avatar answered Jan 21 '23 09:01

JeremyP


nil is absence of value, () is a tuple with 0 elements. Conceptually the same as comparing nil with an empty array: an empty array is not absence of value.

They are simply 2 different and unrelated things.

Just try this in a playground:

var x: Int?
x = () // <== () is not convertible to Int

that produces an error.

like image 23
Antonio Avatar answered Jan 21 '23 09:01

Antonio