iOSGeek
iOSGeek

Reputation: 5587

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 ?

Upvotes: 4

Views: 6968

Answers (3)

Suraj K Thomas
Suraj K Thomas

Reputation: 5883

Functions are first class objects in Swift . They have a type

func nothing(){
    return
}

Actual representation of the above function is like this

func nothing()->(){
        return
    }

In the above code the type of the function is an empty tuple

"()"

If you assign the above function to some variable , we can see the returned tuple

enter image description here

Upvotes: 0

dfrib
dfrib

Reputation: 73216

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.

Upvotes: 11

zneak
zneak

Reputation: 138251

In that case, return only means "leave the function".

Upvotes: 5

Related Questions