Until this point, our functions have only printed values to the terminal. Although useful, functions are a lot more powerful when they are able to pass values out of a function using a return
statement. Passing a value from a function allows us to use it in other functions or save it in a variable until the need for it arises.
If we intend for a function to return a value, we must specify that value’s return type in the function definition. Take a look at the following code:
func funcName() -> Int {
return 5
}
The function above specifies that it returns a value of type, Int
in its definition. Within the body, the return
statement includes 5
which matches the return type.
Note: Not specifying a return type or omitting a return
statement in a function that expects a return will result in an error.
Let’s see a return
statement in action. The following program determines a user’s age given their birth year and the current year:
let birthYear = 1994 var currentYear = 2021 func findAge() -> Int { return currentYear - birthYear }
- The
findAge()
function returns a value of the type,Int
. - Within the body of
findAge()
, areturn
statement is used to return the difference between thecurrentYear
andbirthYear
from the function. - The
return
statement ends the execution of a function.
To see the output of this function, we can:
1. Wrap the function call directly in a print()
statement:
print(findAge()) // Prints: 27
2. Save the function call in a variable and then use a print()
statement to output the value of the variable:
var age = findAge() print(age) // Prints: 27
We’ll practice with both strategies going forward.
Instructions
Earlier in the course, we created a BMI calculator that determined a person’s Body Mass Index given their height and weight. We’ll improve upon this program by making it reusable with a function.
First, declare a function, findBMI()
in BMI.swift that returns a Double
value.
Note: You will see an error in the terminal on the right, but it will go away in the next step when we populate the body of the function with code. Why do you think there’s an error? (Check your answer in the hint!)
Within the findBMI()
function, we’ll use the following formula as a guide to set up an expression that calculates the BMI using weight
and height
:
Translate the right side of the formula into code, and return
it from the function.
Call the function and wrap it in a print()
statement to see its output.