Swift - Function Variable Parameters

Introduction

To define a function that accepts a variable number of arguments, add three dots to your parameter.

For example, to define a function that calculates the average of a series of numbers passed in as arguments.

In this case your function can be defined as follows:

func average (nums: Int... ) -> Float {
   var sum: Float = 0
   for num in nums {
      sum += Float (num)
   }
   return sum/Float(nums.count)
}

The ... (three periods) indicates that the parameter accepts a varying number of arguments, which in this case are of type Int.

A parameter that accepts a variable number of values is known as a variadic parameter.

You can call the function by passing it arguments of any length:

Demo

func average (nums: Int... ) -> Float {
   var sum: Float = 0
   for num in nums {
      sum += Float (num)//  ww w.  j av a  2 s  .com
   }
   return sum/Float(nums.count)
}
print(average(1,2,3))        //2.0
print(average(1,2,3,4))      //2.5
print(average(1,2,3,4,5,6))  //3.4

A variadic parameter must appear last in the parameter list.

If you have a function that accepts default parameter values, the variadic parameter must be last in the parameter list.

Related Topic