Problems summing an array using a loop for fast

I am trying to iterate over an array and summarize all the values ​​using these generics:

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) 

This gives me the following errors:

Binary operator '+' cannot be applied to operands of type 'Int' and 'A' relative to the line sum = sum + number

and

Int is not convertible to 'U' relative to line return sum

I know this is best done 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 have never directly stated that T is Int.

+5
source share
1 answer

In your reduceDaArray() function

 var sum = 0 

declares an integer instead of using the given startingValue . AND

 sum = sum + number 

tries to add a shared array to this integer, instead of using the given summed closure.

So what you probably meant

 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 
+3
source

All Articles