在swift中使用for循环来总结数组的问题

时间:2023-01-04 21:23:02

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

对于行sum = sum + number,二进制运算符'+'不能应用于'Int'和'A'类型的操作数

and

Int is not convertible to 'U' with regards to the line return sum

关于行返还总和,Int不能转换为'U'

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.

我知道这可以通过reduce方法更好地完成,但我想使用迭代完成任务以获得一些练习。为什么会出现这些错误?我从未明确表示T是Int。

1 个解决方案

#1


3  

In your reduceDaArray() function,

在reduceDaArray()函数中,

var sum = 0

declares an integer instead of using the given startingValue. And

声明一个整数而不是使用给定的startingValue。和

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

#1


3  

In your reduceDaArray() function,

在reduceDaArray()函数中,

var sum = 0

declares an integer instead of using the given startingValue. And

声明一个整数而不是使用给定的startingValue。和

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