I'm trying to iterate through an array and sum up all the values using generics like so:
func reduceDaArray <T, U>(a: [T], startingValue: U, summed: (U, T) -> U) -> U {
var sum = 0
for number in a {
sum = sum + number
}
return sum
}
reduceDaArray([2,3,4,5,6], 2, +) //(22)
It's giving me the following errors:
Binary operator '+' cannot be applied to operands of type 'Int' and 'A' with regards to the line sum = sum + number
and
Int is not convertible to 'U' with regards to the line return sum
I know this is accomplished better with the reduce method, but I wanted to complete the task using iteration for this instance to get some practice. Why are these errors occurring? I never explicitly stated that T is an Int.
In your reduceDaArray() function,
var sum = 0
declares an integer instead of using the given startingValue.
And
sum = sum + number
tries to add a generic array element to that integer, instead of using
the given summed closure.
So what you probably meant is
func reduceDaArray <T, U>(a: [T], startingValue: U, summed: (U, T) -> U) -> U {
var sum = startingValue
for number in a {
sum = summed(sum, number)
}
return sum
}
which compiles and works as expected:
let x = reduceDaArray([2, 3, 4, 5, 6], 2, +)
println(x) // 22
let y = reduceDaArray([1.1, 2.2], 3.3, *)
println(y) // 7.986
let z = reduceDaArray(["bar", "baz"], "foo") { $0 + "-" + $1 }
println(z) // foo-bar-baz
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