Swift: In-Out Parameters

In-Out Parameters in Swift:

We’ve used variable values as arguments in some of our previous functions. We could return a completely different value, but we couldn’t change the argument variable directly. A function can reassign the value of a variable passed in as an argument using an in-out parameters in Swift.

Because a function with an inout parameter is expected to change the value of its argument, only variables – not constants or literals – can be passed in when the function is called.

After the parameter name and before the type, an inout parameter is declared in the function definition:

func funcName(parameterName: inout parameterType) -> returnType {
  // body of function

Assume we have a program that turns on the bike’s backlight when the brake is applied. The following function, which uses an inout parameter, can be set up:

var backLight = false ;  
func bikeBreak(brake: Bool, redLight: inout Bool) {
  if brake {
    redLight = true ;
  } else {
    redLight = false ;

The backlight on the bike is currently false. The function has two parameters: brake and redLight, which is an inout parameter. We use a conditional in the body of the function to assign a value to backLight. We don’t return any values from the function, as you can see.

We must call this function in the following format to get it to work:

bikeBreak(brake: true, redLight: &backLight) ;

An ampersand, &, must be used directly before the variable name that will act as its argument when a function that uses an inout parameter is called. This symbol tells the computer that the variable can be changed.

The function’s if statement is executed after the real value for the brake is set to true. The variable backLight takes on the new value as redLight becomes true.

print(backLight) ; // Prints: true

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: