Menu
Coddy logo textTech

Return Values

Part of the Fundamentals section of Coddy's Swift journey — lesson 53 of 86.

So far, our functions have performed actions like printing messages. But often you need a function to calculate something and give back a result. This is where return values come in.

To make a function return a value, add an arrow (->) followed by the return type after the parentheses, then use the return keyword:

func add(a: Int, b: Int) -> Int {
    return a + b
}

let sum = add(a: 3, b: 5)
print(sum)  // Output: 8

The -> Int tells Swift this function returns an integer. The return statement sends the value back to wherever the function was called. You can then store that value in a variable, use it in calculations, or pass it to another function.

func multiply(x: Int, y: Int) -> Int {
    return x * y
}

let result = multiply(x: 4, y: 3) + 10
print(result)  // Output: 22

Functions can return any type—String, Double, Bool, and more. The return type must match what you actually return:

func isEven(number: Int) -> Bool {
    return number % 2 == 0
}

print(isEven(number: 4))  // Output: true
challenge icon

Challenge

Easy
Write a function calculateArea that takes width and height and returns the area of a rectangle.

Multiply the width by the height to calculate the area.

Parameters:

  • width (Int): The width of the rectangle
  • height (Int): The height of the rectangle

Returns: The area of the rectangle (Int)

For example, if width is 5 and height is 3, the function returns 15.

Cheat sheet

Functions can return values using the return keyword. Specify the return type with an arrow (->) after the parentheses:

func add(a: Int, b: Int) -> Int {
    return a + b
}

let sum = add(a: 3, b: 5)
print(sum)  // Output: 8

The return type must match the value being returned. Functions can return any type—Int, String, Double, Bool, etc.:

func isEven(number: Int) -> Bool {
    return number % 2 == 0
}

print(isEven(number: 4))  // Output: true

Returned values can be stored in variables or used directly in expressions:

func multiply(x: Int, y: Int) -> Int {
    return x * y
}

let result = multiply(x: 4, y: 3) + 10
print(result)  // Output: 22

Try it yourself

func calculateArea(width: Int, height: Int) -> Int {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals