Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing in variable number of args from one function to another in Swift [duplicate]

Tags:

swift

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
}
like image 793
Willam Hill Avatar asked Jun 08 '14 21:06

Willam Hill


1 Answers

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
}
like image 55
Connor Avatar answered Oct 17 '22 09:10

Connor