0

Can someone please tell me how I am failing here?

I have a Struct called cardView, in which I predefine an option called currentIndex and define it as an Integer.

When I from a function inside my struct try to add to currentIndex I get a compiler error as the topic says.

Here's how it looks:

struct cardView {
    var currentIndex: Int = 0
    func addToIndex() {
        currentIndex++
    }
}

The cardView struct and function is initialized from my viewController.

linuxqwerty
  • 198
  • 16
Ole Haugset
  • 3,709
  • 3
  • 23
  • 44

2 Answers2

4

You can change struct variables from outside of that struct, but not from within its own functions, you need to add the keyword mutating before fun.

struct cardView {
var currentIndex: Int = 0
    mutating func addToIndex() {
        currentIndex++
    }
}
Swinny89
  • 7,273
  • 3
  • 32
  • 52
1

The method is changing the internal status, so it must be declared as mutating:

mutating func addToIndex() {
^^^^^^^^

Note that this is needed for value types only - classes don't need it, as you can see by just turning the structure into a class.

Antonio
  • 71,651
  • 11
  • 148
  • 165