Return values
All of the functions you’ve seen so far have performed a simple task, namely, printing out something. Functions can also return a value. The caller of the function can assign the return value to a variable or constant or use it directly in an expression.
This means you can use a function to manipulate data. You simply take in data through parameters, manipulate it and then return it. Here’s how you define a function that returns a value:
func multiply(_ number: Int, by multiplier: Int) -> Int { return number * multiplier
}
let result = multiply(4, by: 2)
To declare that a function returns a value, after the set of parentheses and before the opening brace, you add a -> followed by the type of the return value. In this example, the function returns an Int.
Inside the function, you use a return statement to return the value. In this example, you return the product of the two parameters.
It’s also possible to return multiple values through the use of tuples:
func multiplyAndDivide(_ number: Int, by factor: Int)
-> (product: Int, quotient: Int) { return (number * factor, number / factor)
}
let results = multiplyAndDivide(4, by: 2) let product = results.product
let quotient = results.quotient
This function returns both the product and quotient of the two parameters; it returns a tuple containing two Int values with appropriate member value names.
The ability to return multiple values through tuples is one thing that makes it such a pleasure to work with Swift. And it turns out to be a very useful feature, as you’ll see shortly.