Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues summing up array using for loop in swift

Tags:

arrays

swift

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.

like image 209
Roger Yelnats Avatar asked Oct 20 '22 13:10

Roger Yelnats


1 Answers

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
like image 67
Martin R Avatar answered Oct 22 '22 21:10

Martin R