WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

When to use variadic functions

Paul Hudson    @twostraws   

Updated for Xcode 14.2

Swift’s variadic functions let us accept any number of parameters of the same type, separated by a comma. Inside the function they are handed to us as an array, which we can index into, loop over, and so on.

The power of variadic parameters is that we can treat them as if they weren’t variadic most of the time. For example, if you had an open() function that opened a file for editing in Preview, TextEdit, or whatever was the correct program, you might call it like this:

open("photo.jpg")

But that same function could take a variadic parameter – lots of filenames to open, so several could be opened at once:

open("photo.jpg", "recipes.txt", "myCode.swift")

So, by making that parameter variadic, we can open up a whole range of additional functionality without having to change the way the function is called – it’s really useful!

As for when you should use them, chances are you won’t use them that much while you’re learning because you’re going to be focused on very specific problems that are usually fairly small. But as your skills increase, you’ll find that you can change your existing functions to make them variadic without breaking any of your code – you can add functionality without changing what you already have.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.