协议扩展,变异功能 [英] Protocol Extension, Mutating Function
问题描述
我正在使用swift 2.0,我在协议上有一个协议和一个扩展来创建一个方法的默认实现,代码是休闲:
I am using swift 2.0, I have a protocol and an extension on the protocol to create a default implementation of a method, the code is as fallows:
protocol ColorImpressionableProtocol {
var lightAccentColor: UIColor? {get set}
var accentColor: UIColor? {get set}
var darkAccentColor: UIColor? {get set}
var specialTextColor: UIColor? {get set}
mutating func adoptColorsFromImpresion(impresion: ColorImpressionableProtocol?)
}
extension ColorImpressionableProtocol {
mutating func adoptColorsFromImpresion(impresion: ColorImpressionableProtocol?){
lightAccentColor = impresion?.lightAccentColor
accentColor = impresion?.accentColor
darkAccentColor = impresion?.darkAccentColor
specialTextColor = impresion?.specialTextColor
}
}
我稍后在我的代码中尝试调用此方法并获得了错误如下:
I am later on in my code trying to call this method and am getting an error that reads:
不能在不可变值上使用变异成员:'self'是不可变的
"cannot use mutating member on immutable value:'self' is immutable"
代码是休闲:
init(impresion: ColorImpressionableProtocol?){
super.init(nibName: nil, bundle: nil)
adoptColorsFromImpresion(impresion)
}
我唯一可以做的事情认为在这种情况下,'Self'是一个协议,而不是一个类。但是我必须遗漏一些使这个概念起作用的东西,一个由协议定义的方法的默认实现,该协议编辑同样协议定义的值。
The only thing I can think of is that 'Self' in this case is a protocol, not a class. However I have to be missing something to make this concept work, A default implementation of a method defined by a protocol that edits values also defined by the same protocol.
谢谢为了你的帮助和时间:)
Thank you for your help and time :)
推荐答案
如果你打算只为课程使用协议,你可以赚
它是类协议(并删除变异
关键字):
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?)
}
然后
init(impresion: ColorImpressionableProtocol?){
super.init(nibName: nil, bundle: nil)
adoptColorsFromImpresion(impresion)
}
编译没有问题。
这篇关于协议扩展,变异功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!