我有课Transaction
其中有一个变量金额类型的Int
。
我想从另一个班级访问它,我有一个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 类型。
let
创造一个不可变的价值。你需要使用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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)