extension Array {
func sum() -> Int {
var sum = 0
for num in self {
sum += num
}
return sum
}
}
[1,2,3].sum()
This code shows what I would like to do. Though i get an error on the this line: sum += num
. The error i get is: Could not find an overload for '+=' that accepts the supplied arguments
.
I assume the error has something to do with the fact that Array can contain lots of different types, not just Int, so it's bugging out. But how to fix?
There isn't currently a way to extend only a particular type of Array
(Array<Int>
in this case). That'd be a great request to file at bugreport.apple.com
In the meantime you can do this (not in an extension):
func sum(ints:Int[]) -> Int {
return ints.reduce(0, +)
}
All that's needed is an explicit cast to Int
:
extension Array {
func Sum() -> Int {
var sum = 0
for num in self {
sum += (num as Int)
}
return sum
}
}
println([1,2,3].Sum()) //6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With