Created
June 3, 2014 18:03
-
-
Save SlaunchaMan/c234254fa15450ba8f65 to your computer and use it in GitHub Desktop.
Swift Averages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
OK, I fixed it by making a third function that just takes a regular ol’ array of Int
s:
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
}
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
Trying to extend some code from Apple’s sample. I get this error:
Is it not possible to pass variable arguments from one function to another that also takes variable arguments?