Skip to content

Instantly share code, notes, and snippets.

@SlaunchaMan
Created June 3, 2014 18:03
Show Gist options
  • Save SlaunchaMan/c234254fa15450ba8f65 to your computer and use it in GitHub Desktop.
Save SlaunchaMan/c234254fa15450ba8f65 to your computer and use it in GitHub Desktop.
Swift Averages
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
func averageOf(numbers: Int...) -> Int {
var sum = sumOf(numbers)
return sum / numbers.count
}
averageOf(1, 2, 3)
@SlaunchaMan
Copy link
Author

Trying to extend some code from Apple’s sample. I get this error:

Could not find an overload for '__conversion' that accepts the supplied arguments

Is it not possible to pass variable arguments from one function to another that also takes variable arguments?

@SlaunchaMan
Copy link
Author

OK, I fixed it by making a third function that just takes a regular ol’ array of Ints:

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

func sumOf(numbers: Int...) -> Int {
    return arraySum(numbers)
}

func averageOf(numbers: Int...) -> Int {
    var sum = arraySum(numbers)

    return sum / numbers.count
}

@eonist
Copy link

eonist commented Mar 23, 2017

What about [0,0,0,0,5].avg//1

Should be 5 no?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment