Binary operator + = cannot be applied to two Int operands
I am creating a simple structure.
struct Expenses {
var totalExpenses:Int = 0
func addExpense(expense: Int) {
totalExpenses += expense
}
}
It produces an error at the beginning of the line totalExpenses += expense
Error message
the binary operator + = cannot be applied to two Int operands.
Why am I getting an error and how can I fix this problem?
source to share
You need to specify addExpense
- this is a function mutating
, for example:
struct Expenses {
var totalExpenses:Int = 0
mutating func addExpense(expense: Int) {
totalExpenses += expense
}
}
From the documentation:
Structures and enumerations are value types. By default, properties of a value type cannot be changed from its Methods instance.
However, if you need to change the properties of your structure or enumeration within a particular method, you can choose to mutate the behavior for that method.
For more information see Rapid Programming Language: Methods
source to share