DAY #14

Variatic parameters

Swift has variadic parameters. This allows you to put multiple things into a function without having to use an array. It is notated with the range syntax “…”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
//EXAMPLE FROM https://www.swiftbysundell.com/tips/the-power-of-variadic-parameters/
// 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)

You always have the option of using an array if you want, like:

1
 send(message, attaching: [])

But this is a cool alternative.

I had no idea this existed. I was looking for something else when doing research. Swift always surprises me.

Originally published 04/16/2021 @ https://pittcsc.org/ Discord

Published here on 09/08/2022. Blog published date reflects the original date of publication.