How to use Variadic Parameters in Swift 5+?

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

A variadic parameter accepts zero or more values of a specified type. When creating API it seems more developer-friendly as we don’t needs to generate an array at the caller site in order to pass multiple arguments.

The variadic parameter using three dots can be passed a varying number of input values when the function is called.

KEY TAKEWAYS

The values passed to a variadic parameter are made available within the function’s body as an array of the appropriate type.
// Variadic parameter can be used any number of arguments(here voucherValues)
func redeemVouchers(_ greetings: String, voucherValues: Int...) -> String {
    let voucherText = voucherValues.count > 0 ? " You have redeemed " + "\(voucherValues.reduce(0, +)) €" : ""
    return greetings + voucherText
}

// No variadic parameter
redeemVouchers("Congratulation!")
// "Congratulation!"

// Multiple variadic parameter
redeemVouchers("Congratulation!", voucherValues: 12, 23, 10)
// "Congratulation! You have redeemed 45 €"

// Single variadic parameter
redeemVouchers("Congratulation!", voucherValues: 10)
// "Congratulation! You have redeemed 10 €"

Recently released Swift 5.4 brings support for multiple variadic parameters. However, you can not use variadic parameters as inout parameters.

func redeemVouchers(_ greetings: String..., voucherValues: String...) {
  ...
}

redeemVouchers("Congratulation!" "Mr. Robot", voucherValues: 12, 23, 10)


✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.