18

I can't quite understand why I can't past an Int[] from one function to another:

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

func average(numbers:Int...) -> Double {
    var sum = sumOf(numbers)

    return Double(sum) / Double(numbers.count)
}

This gives me the following error:

Playground execution failed: error: <REPL>:138:19: error: could not find an overload for '__conversion' that accepts the supplied arguments

var sum = sumOf(numbers)
          ^~~~~~~~~~~~~~

Thanks for your help!

2 Answers 2

20

The numbers: Int... parameter in sumOf is called a variadic parameter. That means you can pass in a variable number of that type of parameter, and everything you pass in is converted to an array of that type for you to use within the function.

Because of that, the numbers parameter inside average is an array, not a group of parameters like sumOf is expecting.

You might want to overload sumOf to accept either one, like this, so your averaging function can call the appropriate version:

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

2 Comments

They should add this to the language. For example c# allows you to simply pass the array as well.
The new syntax requires [Int] instead of Int[]
1

I was able to get it to work by replacing Int... with Int[] in sumOf().

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

func average(numbers: Int...) -> Double {
    var sum = sumOf(numbers)

    return Double(sum) / Double(numbers.count)
}

average(3,4,5)

Your problem is Int... is a variable amount of Ints while Int[] is an array of Int. When sumOf is called it turns the parameters into an Array called numbers. You then try to pass that Array to sumOf, but you had written it to take a variable number of Ints instead of an Array of Ints.

1 Comment

Only issue with this approach is that sumOf(3, 4, 5) will no longer work, so you'd have to do the overload approach as suggested by Nate Cook above. (It seems to me that conversion should be implicit, but perhaps that violates the "no implicit conversions" philosophy Swift has adopted.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.