Skip to main content

Variadic Parameters In Swift


Variadic parameters allows to pass-in the parameter of a method either a single or collection of specific types.The benefit of this is a more clean code and easier implementation.

Example:
mutating func add(_ newElement: SomeElement…) {
    array.append(contentsOf: newElement)
}
Variadic parameters are defined by Type following the three dots

This add(_:) method now allows a single element to be added or an array of elements of type SomeElement.
struct SomeElement {
    let title: String
}

var dataController = DataController()

/// Add only a single content item:
dataController.add(SomeElement(title: "Blog post 1"))

/// Add multiple items:
dataController.add(SomeElement(title: "Blog post 2"), SomeElement(title: "Blog post 3"))
Since Swift 5.4, there is a possibility of adding multiple variadic parameters.

LIMITATIONS

Passing an array of [SomeElement] directly to the method is still not supported. As a workaround, a developer needs to use method overloading and add a method with the same name, which accepts array of [SomeElements] as a parameter to achieve this.
mutating func add(_ newElement: SomeElement…, newUsers: SomeUser…) {
    elements.append(contentsOf: newElement)
    users.append(contentsOf: newUsers)
}

mutating func add(_ newElement: [SomeElement]) {
    elements.append(contentsOf: newContent)
}

Comments