What are variadic functions in Swift?

Overview

In Swift, variadic functions accept a variable number of arguments. Three dots, ..., represent the variable arguments. There can only be one variadic parameter in the function’s parameter/argument list.

Syntax

The syntax to specify a variadic parameter of a function is as follows:

public func functionName(parameterName:dataType...)

Example

func educativeAuthors(_ name: String...)

The above function educativeAuthors accepts a variable number of strings as a parameter called name.

Parameter

The method takes the values provided to a variadic argument available as an array of the appropriate type.

For example, in the above function educativeAuthors, the variadic parameter name of type String... is made available within the function’s body as a constant array called name of type [String].

Refer to the following code to access the variadic parameter values in the function body.

public func educativeAuthors(_ param1:Double, _ names:String...) -> () {
for author in names {
print("\(author)")
}
}
educativeAuthors(2.4, "john", "sam", "celeste", "gaby")

Explanation

  • Lines 1-6: We define a function called educativeAuthors that accepts a variable number of strings as a parameter called names.
    • Lines 3-5: We print all the values in the names array.
  • Line 8: We invoke the educativeAuthors function.

Free Resources