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 :-)
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)
})
}