Issues summing up array using for loop in swift -
i'm trying iterate through array , sum values using generics so:
func reducedaarray <t, u>(a: [t], startingvalue: u, summed: (u, t) -> u) -> u { var sum = 0 number in { sum = sum + number } return sum } reducedaarray([2,3,4,5,6], 2, +) //(22)
it's giving me following errors:
binary operator '+' cannot applied operands of type 'int' , 'a'
regards line sum = sum + number
and
int not convertible 'u'
regards line return sum
i know accomplished better reduce method, wanted complete task using iteration instance practice. why these errors occurring? never explicitly stated t int.
in reducedaarray()
function,
var sum = 0
declares integer instead of using given startingvalue
. ,
sum = sum + number
tries add generic array element integer, instead of using given summed
closure.
so meant is
func reducedaarray <t, u>(a: [t], startingvalue: u, summed: (u, t) -> u) -> u { var sum = startingvalue number in { sum = summed(sum, number) } return sum }
which compiles , works 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
Comments
Post a Comment