6

The Swift language guide shows you how to create functions that take in variable arguments. It also notes that the arguments are collected into an array.

So if I have the example function sumOf, as noted in the guide:

func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}

And a second function that also takes a variable number of arguments, how can you pass the same var_args value from the second into the first?

func avgOf(numbers: Int...) -> Int {
    // Can't do this without the complier complaining about:
    // "error: could not find an overload for '__conversion' that accepts the supplied arguments"
    var sum = sumOf(numbers)
    var avg = sum / numbers.count
    return avg
}
1

1 Answer 1

3

sumOf and averageOf both take a variadic paramter of Int, which is not the same as an Array of Int. The variadic paramter is converted into an Array, though which is what numbers it, but then you aren't able to call sumOf on numbers.

You can fix this by making a sumOf function that takes a variadic parameter and one that takes an arrary like this:

func sumOf(numbers: Int...) -> Int {
    return sumOf(numbers)
}
func sumOf(numbers: Int[]) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
Sign up to request clarification or add additional context in comments.

1 Comment

It also turns out that splatting is not yet supported: devforums.apple.com/message/970958#970958

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.