Swift: Returning a Value

Return Value in Swift:

Our functions have only printed values to the console up to this point. Although functions become much more powerful when they can pass values out of them via the return statement. We can use a value passed from a function in other functions or save it in a variable until we need it again.

If a function is to return a value, the return type of that value must be specified in the function definition. Take a look at the code below:

func funcName() -> Bool {
 return true

In its definition, the function above specifies that it returns a value of Bool type. The return statement includes true in the body, which matches the return type.

Note: An error will occur if you don’t specify a return type or omit a return statement in a function that expects one.

Let’s look at an example of a return statement. Given a user’s weight and height, the following program calculates their BMI:

var weight = 65.9 ;
var height = 1.82 ;
func findBMI() -> Double {
  return weight / (height * height);

  • The findBMI() function returns a value of the type, Double.
  • A return statement is used within the body of findBMI() to return the BMI value using weight and height.
  • The return statement brings a function’s execution to an end.

We can look at the output of this function by:

1. Use a print() statement to wrap the function call:

print(findBMI()); // Prints: 19.89

2. Save the function call in a variable, then print the variable’s value using the print() statement:

var BMI = findBMI();
print(BMI) // Prints: 19.89

We’ll continue to practice with both strategies in the future.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: