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?

+3


source to share


3 answers


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

+1


source


You cannot change the structure unless you are using the mutating keyword, the default structure is not changed, try this:



mutating func addExpense(expense: Int) { ... }

      

+1


source


I ran into this problem the other day, either using the keyword mutating

in your function or instead struct

instead class

.

+1


source







All Articles