1

I'm currently working on a Swift project and encountered an issue when trying to pass a variadic parameter from one function to another.

Specifically, I expected that I could directly pass the variadic parameter from one function to another that also accepts variadic parameters. However, this approach doesn’t seem to work as I expected, and I’m not sure why.

Here’s a simplified version of my code:

func myFunctionA(integers: Int...) {
    // Some operations with integers
}

func myFunctionB(integers: Int...) {
    myFunctionA(integers: integers) // This line throws an error
    // --> Cannot pass array of type 'Int...' as variadic arguments of type 'Int'
}

In this code, myFunctionB is supposed to accept a list of integers, and then pass them to myFunctionA. However, I’m getting an error on the line where myFunctionA is called, and I'm not sure why the variadic parameter can’t be passed along like this.

Could someone explain why this doesn’t work in Swift? Is there a correct way to pass variadic parameters from one function to another, or am I approaching this incorrectly?


For broader context, myFunctionA is part of a centralised, shared set of methods. myFunctionB is in a convenience wrapper class, and thought being able to pass the parameter onwards would maintain the code simplicity.

I have tried expanding the array back into a variadic parameter:

func myFunctionB(integers: Int...) {
    myFunctionA(integers: integers...)
}

But then I get a new error of:

Cannot convert value of type '()' to expected argument type 'Int' and Cannot convert value of type 'Int...' to expected argument type 'UnboundedRange_'

2
  • Can you write a [Int] overload and change the existing methods to delegate to that instead? Commented Aug 10, 2024 at 8:40
  • "However, this approach doesn’t seem to work as I expected, and I’m not sure why" It's because variadics in Swift are not very good. :) Or perhaps I should say they are not very real. Swift is not Ruby: you can't "splat". Basically it's just a huge hole in the language that has been there from day one. Basically a variadic argument can only be a literal list of values; you can't "pass" something that you receive in one function into a variadic argument of another. Commented Aug 10, 2024 at 14:12

1 Answer 1

0

A possible solution is to specify the type in myFunctionA as protocol CVarArg

func myFunctionA(integers: CVarArg) {
    // Some operations with integers
}

func myFunctionB(integers: Int...) {
    myFunctionA(integers: integers)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.