Friday, April 22, 2016

Variadic Parameters (or, what are those three dots after the parameter type?) (Swift 2.2)

Swift gives us a cool way to indicate a variable number of parameters of a specified type in a function signature. This is called "variadic parameters". The parameter list is automatically converted to an array under the hood.

Note: A variadic argument can consist of zero or more values. As a result, the array could be empty. Make sure to account for this in your code, if necessary!

Here's what it looks like:
func doSomethingWithTheseColors(colors: UIColor...) { 
    // treat the list of colors as an array, eg:
    for (theIndex, theColor) in colors.enumerate() {
        print("\(theIndex). \(theColor.description)")
    } 
}
This function can then be called like this:
doSomethingWithTheseColors()
or
doSomethingWithTheseColors(UIColor.redColor)
or
doSomethingWithTheseColors(UIColor.redColor, UIColor.greenColor, UIColor.blueColor) 
You can call the function with as many arguments as you want (of the specified type, of course) - or none at all.

Resource: The Swift Programming Language (Swift 2.2) -> Functions (See Variadic Parameters)

No comments:

Post a Comment