Swift Returning Values
Returning a value means a function hands a result back to the code that called it. The call itself then stands for that result.
Returning a number
The function declares an Int result after the arrow. The body returns n times 3 and the call with 4 stores 12.
func triple(n: Int) -> Int {
return n * 3
}
let result = triple(n: 4)
print(result)Two spellings, one result
The first body uses the return keyword on its line. The second body holds one expression and needs no keyword.
func doubleLong(n: Int) -> Int {
return n * 2
}
func doubleShort(n: Int) -> Int {
n * 2
}
print(doubleLong(n: 6))
print(doubleShort(n: 6))An early return
A score of 50 or more meets the if condition and the function ends there. A lower score skips the if body and reaches the last line.
func label(score: Int) -> String {
if score >= 50 {
return "Pass"
}
return "Try again"
}
print(label(score: 80))
print(label(score: 30))Two values in one result
The result type in parentheses holds two Int values. The prints show the pair as a whole and then one part at a time.
func minMax(a: Int, b: Int) -> (Int, Int) {
if a < b {
return (a, b)
}
return (b, a)
}
let pair = minMax(a: 9, b: 4)
print(pair)
print(pair.0)
print(pair.1)A missing return
This function declares an Int result but its body only prints. The compiler rejects the program with one error.
func showSquare(n: Int) -> Int {
print(n * n)
}
let value = showSquare(n: 5)
print(value)Example
func price(count: Int, each: Int) -> Int {
return count * each
}
let total = price(count: 3, each: 7)
print(total)
print(total + 1)Key points
- An arrow and a type after the parameter list declare the result type.
- The return keyword hands a value back and ends the function.
- A body with one expression can skip the return keyword.
- Code can store a result in a constant and use it later.
- An early return inside an if leaves the function at once.
- A tuple result packs two values into one result.
In this example, the price function multiplies count by each and returns the product. The call with 3 and 7 stores 21 in total. The first print shows 21 and the second print shows 22.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the return keyword do inside a function?