在swift中for循环中对象数组的Sum元素:Sum变量不保留值?

时间:2015-03-10 13:58:07

标签: ios arrays swift for-loop

我写了我认为是基本函数来总结数组的值并计算预算中剩余的数量。我使用for循环来对数组的元素求和,然后从预算中减去该值。但是,由于某种原因,sum的值在for循环中正确更新,但for循环中的sum值始终为零。在下面,println“循环中的Sum”是正确的,但println“Sum is”总是等于0. dataModel.spendingDataDisplay是一个对象数组。谢谢你的帮助。

func amountLeftToSpend ()->Double {
        var sum:Double = 0.0
        for spendingItem in dataModel.spendingDataDisplay {
            var sum = spendingItem.amountSpent + sum
            println("Spending Item .amountSpent\(spendingItem.amountSpent)")
            println("Sum in the loop is \(sum)")
        }
        println("Sum is \(sum)")
        let amountLeftInBudget = dataModel.settingsData.weeklyBudget - sum
        println("Amount Left in Budget is \(amountLeftInBudget)")
        return amountLeftInBudget
    }

4 个答案:

答案 0 :(得分:7)

正如其他人所指出的,你有两个sum变量。所以你可以通过消除内部var引用来解决这个问题:

var sum:Double = 0.0
for spendingItem in dataModel.spendingDataDisplay {
    sum += spendingItem.amountSpent
}

或者,如果spendingDataDisplay是Swift数组,您还可以使用reduce方法:

let sum = dataModel.spendingDataDisplay.reduce(0.0) { $0 + $1.amountSpent }

答案 1 :(得分:2)

看起来你正在更新for循环中的局部变量sum,而不是在循环外声明为Double的变量。这就是为什么" Sum是"总是0.我实际上并不确定循环中的" Sum"鉴于你的代码是正确的,但我对Swift不是很好。

我认为你需要改变 var sum = spendingItem.amountSpent + sum

sum += spendingItem.amountSpent

答案 2 :(得分:1)

var sum:Double = 0.0
    for spendingItem in dataModel.spendingDataDisplay {
        var sum = spendingItem.amountSpent + sum
在第三行

重新声明变量sum。它应该是:

var sum:Double = 0.0
    for spendingItem in dataModel.spendingDataDisplay {
        sum = spendingItem.amountSpent + sum

我不确定它确实有效...

xcode playground with example showing it doesn't work

有趣的是,我们只在其函数上下文之外得到编译器警告

compiler warning

答案 3 :(得分:1)

您可以使用reduce功能来避免此类错误。

func amountLeftToSpend ()->Double {
    let sum = reduce(dataModel.spendingDataDisplay, 0.0) { $0 + $1.amountSpeed }

    println("Sum is \(sum)")
    let amountLeftInBudget = dataModel.settingsData.weeklyBudget - sum
    println("Amount Left in Budget is \(amountLeftInBudget)")
    return amountLeftInBudget
}