iOSGeek iOSGeek - 3 months ago 8
Swift Question

Return in function without return value in Swift

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 ?

Answer

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, called sayGoodbye(_:), which prints its own String 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 type Void. 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.