Articles, podcasts and news about Swift development, by John Sundell.

The power of variadic parameters

Published on 29 Jun 2019

I’m a big fan of functions with variadic parameters in Swift, especially when I want an API to feel a bit more “lightweight”, since no array needs to be created at the call site in order to pass multiple (or zero) arguments.

// When using a variadic parameter, any number of arguments can
// be passed, and the compiler will automatically organize them
// into an array.
func send(_ message: Message, attaching attachments: Attachment...) {
    ...
}

// Passing no variadic arguments:
send(message)

// Passing either a single, or multiple variadic arguments:
send(message, attaching: image)
send(message, attaching: image, document)