Swift 2 Error using mutating function in Protocol extension \"Cannot use mutating member on immutable value: 'self' is immutable

China☆狼群 提交于 2019-11-30 05:35:31

The problem is that, in the protocol you mark the function as mutating, which you need to do if you want to use the protocol on a struct. However, the self that is passed to testFunc is immutable (it's a reference to a instance of the class) and that is tripping up the compiler. This would make sense if testClass was actually a struct and you could make the function mutating to resolve the issue.

I can see two work arounds:

  1. make the protocol class only

    protocol MTKAnimateValueDelegate: class { ...
    
  2. Make testClass a struct and mark testFunc as mutating.

Either way, I think this is a bug that needs to be reported to Apple.

Edit

  1. Another way around it is to make a mutable copy of self
func testFunc() {
    var animValue = MTKAnimateValue(fromValue: 10, toValue: 20, inSeconds: 2)
    animValue.isAnimating = true
    var mutableSelf = self
    mutableSelf.mtkAnimQueAppend(animValue) 
  }

Since mutableSelf is a reference, any changes the mutating function makes will still be reflected in self's state.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!