Reputation: 24902
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 ()?
Upvotes: 5
Views: 678
Reputation: 86651
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) { ... }
Upvotes: 7
Reputation: 72760
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.
Upvotes: 2