3

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?

Shaiful Islam
  • 7,034
  • 12
  • 38
  • 58
Diego Petrucci
  • 221
  • 1
  • 3
  • 11

3 Answers3

1

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

ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
  • Thanks. What would you use in this case, then? A class? – Diego Petrucci May 14 '15 at 15:34
  • If you used a class you wouldn't need to specify the method was `mutating`, but that's not a reason to use a class instead of a struct. I would recommend looking at: http://stackoverflow.com/questions/24232799/why-choose-struct-over-class – ABakerSmith May 14 '15 at 15:36
  • Thanks. My worry was that adding the 'mutating' keyword was somehow bad practice. – Diego Petrucci May 14 '15 at 15:44
  • Its perfectly valid to use structs and `mutating`, I prefer it to using classes as you don't have to worry about memory leaks and such. – ABakerSmith May 14 '15 at 15:47
1

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

mutating func addExpense(expense: Int) { ... }
Greg
  • 25,317
  • 6
  • 53
  • 62
  • This could do with a better error message that mentions that "mutating" is needed. Well, the compiler is quite new... – gnasher729 May 14 '15 at 15:28
  • @gnasher729 Exactly. I missed that part in the doc (first time programming) and I had no idea why I couldn't add two ints. – Diego Petrucci May 14 '15 at 15:35
  • The compiler errors in Swift are pretty awful across the board. All they really mean is "duh, something's wrong...". It's up to you to go figure out what. Worse, sometimes the messages point you in completely the wrong direction. I feel like I'm using a C compiler from the early 1980s again. – Duncan C May 14 '15 at 15:53
1

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

Chackle
  • 2,249
  • 18
  • 34