5

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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.