3
votes

I'm creating a simple struct.

struct Expenses {

    var totalExpenses:Int = 0

    func addExpense(expense: Int) {
        totalExpenses += expense
    }
}

It produce error at the beginning of line totalExpenses += expense The error message is

binary operator += cannot be applied to two Int operands.

Why I am getting the error message and how I can solve this issue?

3
and what is the question? - Shaiful Islam
@ShaifulIslam "How to solve this error?". Adding it right now, thanks. - Diego Petrucci

3 Answers

1
votes

You cannot change struct unless you use mutating keyword, struct is not mutable by default, try this:

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

You need to specify addExpense is a mutating function, like so:

struct Expenses {
    var totalExpenses:Int = 0

    mutating func addExpense(expense: Int) {
        totalExpenses += expense
    }
}

From the documentation:

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method.

For more information see The Swift Programming Language: Methods

1
votes

I came across this issue the other day, either use mutating keyword on your function or define your struct as class instead.