Wesley de Groot's Blog
Variadic Parameters

Back

These versatile constructs allow us to handle a variable number of arguments of the same type within a function.

What are Variadic Parameters?

In Swift, variadic parameters enable a function to accept zero or more values of a specific type.
They come in handy when you want to create a function that can take any number of arguments without specifying the exact count upfront.
Imagine a scenario where you're dealing with a method that often works with individual elements, and you'd rather avoid creating an array just for a single value at the implementation level.

How to Define a Variadic Parameter

To declare a variadic parameter, use a value type followed by three dots ....


Here's an example:

mutating func add(_ newContent: Content...) {
    content.append(contentsOf: newContent)
}

In this snippet:

  • add(_:) is a method that can accept either a single value or multiple values at once.
  • The Content type represents the elements we're adding to our collection.

You can now call this method with one or more Content instances:

var posts = BlogPosts()

// Add a single content item:
posts.add(Content(title: "Blog post 1"))

// Add multiple items:
posts.add(
    Content(title: "Blog post 2"), 
    Content(title: "Blog post 3")
)

Handling Multiple Variadic Arguments

Since Swift 5.4 (shipped with Xcode 12.5), you can define multiple variadic arguments in a method:

mutating func add(_ newContent: Content..., newUsers: User...) {
    content.append(contentsOf: newContent)
    users.append(contentsOf: newUsers)
}

This flexibility allows multiple parameters to receive zero or more values.

Caveats / Limitations

While variadic parameters are powerful, they have some limitations to consider:

Empty Variadic Arguments: You can pass an empty array as a variadic argument. For instance:

struct BlogPosts {
    private(set) var content: [Content] = []

    mutating func add(_ newContent: [Content]) {
        content.append(contentsOf: newContent)
    }
}

var posts = BlogPosts()
    posts.add([])

The same applies when using variadic parameters directly:

struct BlogPosts {
    private(set) var content: [Content] = []

    mutating func add(_ newContent: Content...) {
        content.append(contentsOf: newContent)
    }
}

var posts = BlogPosts()
    posts.add()

Type Consistency: Variadic parameters must have the same type. You cannot mix different types within a single variadic argument.

Conclusion

Variadic parameters are a powerful feature in Swift that allows you to create functions that can accept a variable number of arguments.

Resources:
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/functions/

Read more

Share


Share Mastodon Twitter LinkedIn Facebook
x-twitter mastodon github linkedin discord threads instagram whatsapp bluesky square-rss sitemap