Swift: Variadic Parameters

Variadic Parameters in Swift:

The variadic parameter is another Swift parameter. A variadic parameters in Swift is one that takes zero or more values of the same type. A variadic parameter comes in handy when we need to pass in multiple values for a single parameter.

In the function declaration, a variadic parameter is identified by a name, type, and three consecutive dots .... So, it’s worth noting that a Swift function can only have one variable parameter.

func functionName(paramName: paramType...) -> returnType {
  // body of function
}

Within the body of the function, the values passed for a variadic parameter are interpreted as an array of a specific type. So. let’s look at an application of a variadic parameter.

The following code uses a variable parameter in a function to calculate the average distance between two points:

var total = 0 ;

func avgDistance(lenghts: Int...) -> Int {

  for lenght in lenghts {
    total += lenght ;
  }

  return total / lenghts.count ;
}

In the preceding code:

  • numbers is a variadic parameter that takes zero or more Double values but within the function, it’s interpreted as an Array.
  • Iterate over each lenght in lenghts using a forin loop, adding the value of lenght to the total each time.
  • So, the average is calculated by dividing the total by the number of items, lenght.count, in lenghts, after the forin loop has completed iterating.

With the following distances recorded for 7 days in January 2020, we can use the function:

print(avgDistance(lenght: 220, 240, 270, 228, 286, 254, 281));

// Prints: 254

In the for-in loop, each decimal pass into the function body and iterated over. The following is a breakdown of the values:

Variable Value
total1779
lenghts.count7.0
total / lenghts.count 254

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: