Protocol Extension, Mutating Function

霸气de小男生 提交于 2019-11-28 13:16:51

If you intend to use the protocol only for classes then you can make it a class protocol (and remove the mutating keyword):

protocol ColorImpressionableProtocol : class {

    // ...

    func adoptColorsFromImpresion(impresion: ColorImpressionableProtocol?)
}

Then

init(impresion: ColorImpressionableProtocol?){
    super.init(nibName: nil, bundle: nil)
    adoptColorsFromImpresion(impresion)
}

compiles without problems.

The possible solutions are :

1) Implement a non mutating version of the method where the protocol being adopted. ie: implement the method in adopting class instead as a protocol extension.

2) Make the protocol as class only protocol.If your protocol need to support class only,it's the easiest solution.

3) Make sure only value types adopt this protocol.This may not be useful in all scenarios.

Here is the detailed explanation and solution for this case.

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