Let's take a look at this function:
func nothing(){
return
}
it does not return a value, but we can write return
statement how Swift handle that ? what happens behind the scene does return
without value returns 0 or any value to handle this case ?
The following signatures all return an instance of the empty tuple ()
(typealiased as Void
).
func implicitlyReturnEmptyTuple() { }
func explicitlyReturnEmptyTuple() {
return ()
}
func explicitlyReturnEmptyTupleAlt() {
return
}
In all of the three above, the return type of the function, in the function signature, has been omitted, in which case it is implicitly set to the empty tuple type, ()
. I.e., the following are analogous to the three above
func implicitlyReturnEmptyTuple() -> () { }
func explicitlyReturnEmptyTuple() -> () {
return ()
}
func explicitlyReturnEmptyTupleAlt() -> () {
return
}
With regard to your comment below (regarding body of implicitlyReturnEmptyTuple()
where we don't explicitly return ()
); from the Language Guide - Functions: Functions without return values:
Functions are not required to define a return type. Here’s a version of the
sayHello(_:)
function, calledsayGoodbye(_:)
, which prints its ownString
value rather than returning it:func sayGoodbye(personName: String) { print("Goodbye, \(personName)!") }
...
Note
Strictly speaking, the
sayGoodbye(_:)
function does still return a value, even though no return value is defined. Functions without a defined return type return a special value of typeVoid
. This is simply an empty tuple, in effect a tuple with zero elements, which can be written as()
.
Hence, we may omit return ...
only for ()
-return (Void
-return) function, in which case a ()
instance will be returned implicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With