Cannot invoke “+=” with an argument list of type (Int, @value Int)

别说谁变了你拦得住时间么 提交于 2019-12-31 01:45:31

问题


I have a class Transaction which has a var amount of type Int. I want to access it from another class, where I have an array of Transactions and sum all of their amounts.

So I have this piece of code

func computeTotal()-> Int{
    let total = 0
    for transaction in transactions{
        //get the amounts of each and sum all of them up
        total += transaction.amount
    }
    return total
}

But it gives me an error

Cannot invoke "+=" with an argument list of type (Int, @value Int)

What can cause that? I know that in Swift both operands must be the same type, but they are both of type Int in my code.


回答1:


let creates an immutable value. You need to use var, like:

func computeTotal()-> Int{
    var total = 0
    for transaction in transactions{
        //get the amounts of each and sum all of them up
        total += transaction.amount
    }
    return total
}


来源:https://stackoverflow.com/questions/27405180/cannot-invoke-with-an-argument-list-of-type-int-value-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!