Start learning free

LESSON 41 OF 678 · FUNCTIONS I

Returning from functions in Swift

Lesson

In the previous lessons, we have used functions with no return type in the function declaration. This means the function is not returning any value.

It's also possible to return a value from a function. For this, we need to specify the -> returnType of the function during function declaration.

Inside the function, we can use the return statement to send a value back out of a function.

The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer below):

func plusThree(_ num: Int) -> Int {
	return num + 3
}

// Inside main function:
let answer = plusThree(5)
print(answer) // Output: 8

Here, we have -> Int instead of no return type. This means that the function returns an Int value.

plusThree takes an Int argument for num and returns an Int value equal to num + 3.


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 6
    Ctrl + Enter to check