Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Function Return Types in Swift
Written by Team Kodeco

Functions in Swift can return a value of a specified type. The type of value a function returns is specified by the -> followed by the type, which is written after the function’s name and its parameters. This is called the function’s return type.

Here’s an example of a function that takes two integer parameters, a and b, and returns their sum:

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

let result = addTwoNumbers(a: 2, b: 3)
print(result) // Output: 5

In this example, the function addTwoNumbers takes two parameters of type Int and returns a value of type Int.

Creating a Function with No Return Value

There are several different ways to specify a function doesn’t have a return value: Either don’t use the -> operator, use the -> operator with Void or use the -> operator with an empty tuple ():

func noReturnValueExample1() {
}

func noReturnValueExample2() -> Void {
}

func noReturnValueExample3() -> () {
}

Return Multiple Values from a Function

Returning multiple values from a function can be done using tuple:

func addAndSubtract(a: Int, b: Int) -> (add: Int, subtract: Int) {
    return (a + b, a - b)
}
let result = addAndSubtract(a: 5, b: 3)
print(result.add) // Output: 8
print(result.subtract) // Output: 2

In this example, the function addAndSubtract returns a tuple containing two integers, the sum and difference of the two input parameters.

© 2024 Kodeco Inc.