我有一个类Transaction
,其类型为Int
var amount 。
我想从另一个班级访问它,我有一个array of Transactions
并将所有金额相加。
所以我有这段代码
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
}
但它给了我一个错误
无法使用类型(Int,@ value Int)的参数列表调用“+ =”
导致这种情况的原因是什么?我知道在Swift中,两个操作数必须是相同的类型,但在我的代码中它们都是Int类型。
答案 0 :(得分:3)
let
创建一个不可变的值。您需要使用var
,例如:
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
}