当我这样做时:
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"
}
}
我收到此错误消息: 我读过这个: 不允许部分应用"变异"方法 并且可以看到问题,但无法确定替代代码应该是什么?
我的主要要求是,我想设置一系列"技术",例如递增和递减,然后通过简单的调用"应用"它们。
任何帮助表示赞赏:-(
一种方法是在technique
中接受inout Test
。你也应该做apply
mutating
,因为它无疑会改变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)
})
}