Nil and Void
Disclaimer: The title plagiarised from GNU’s Sather programming language specification
This post is nothing investigative, nor any take away value from it. Consider this a meditation into the philosophy of code or something around the lines, so the following have some significance.
What is Void in Swift?
Void is simply a type alias on an empty tuple.
According to the docs, it is the return type of function that doesn’t specify any return type.
Is in reality
func returnNothing() -> Void {
return Void()
}
This also gives rise to some useless experiments like
let x: [Void] = [Void(), Void(), Void()]
And the size of Void
Why is it there?
Void
is Swift’s representation of a unit type. And unit type is a concept in type theory holding only one value and thus no information.
What is nil in Swift?
nil
is one of the two different variations value possible for an Optional type.
Is in reality
Here x
can take either an Integer value or a nil
value representing absence of an Integer value.
All nils are not the same.
nil
is equal to itself. However, nil
s of two differnt type are not comparable.
let ix: Int? = nil
let fx: Float? = nil
fx == ix // This will raise a type error, since by default Equatable '==' is not defined to compare between different types
Size of nil value
A nil
value has same size as the size reserved for other values of the same type.
var x: Int? = nil
MemoryLayout.size(OfValue: x)