0

When I do this:

struct Test {
  var value: Int = 0

  mutating func increment(amount: Int) { value += amount }
  mutating func decrement(amount: Int) { value -= amount }

  func apply(technique: (Int) -> ()) {
    print("Before:\(value)")
    technique(2)
    print("After:\(value)")
  }

  mutating func main() {
    apply(technique: increment) //Error: "Partial application of 'mutating' method is not allowed"
  }

}

I get this error message: I've read this: Partial application of 'mutating' method is not allowed and can see the problem but can't work out what the alternative code should be?

My key requirement is that I want set up a series of "techniques" such as increment and decrement and then "apply" them with a simple call.

Any help appreciated :-)

Cortado-J
  • 2,035
  • 2
  • 20
  • 32
  • 1
    This is a struct. Note that value types are copied. Just consider what piece of memory would be the one mutated. – Sulthan May 17 '20 at 08:25
  • Thanks Sulthan. And if I change to a class (and drop 'mutating' where it occurs) then all is fine. I'd rather stick with s struct if I can but still can't see how I would change my code to work with a struct? – Cortado-J May 17 '20 at 08:34

1 Answers1

1

One way is to accept an inout Test in technique. Also you should make apply mutating, because it undoubtedly changes the state of Test.

mutating func apply(technique: (inout Test, Int) -> ()) {
    print("Before:\(value)")
    technique(&self, 2) // this is "kind of" analogous to "self.technique(2)"
    print("After:\(value)")
}

mutating func main() {
    apply(technique: {
        $0.increment(amount: $1)
    })
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313