类协议:不能一成不变值使用可变成员:“自我”是不可改变的
问题描述:
我从框架类协议:不能一成不变值使用可变成员:“自我”是不可改变的
public protocol BaseMappable {
/// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process.
mutating func mapping(map: Map)
}
协议,我有我的扩展协议(默认实现)
public protocol DtoResponseRequestActionable: class {
func transferToResponceAction(_ dto: TransferToResponce)
}
extension DtoResponseRequestActionable where Self: BaseMappable {
func transferToResponceAction(_ dto: TransferToResponce) {
var map = Map(mappingType: .toJSON, JSON: [:])
dto.transfering(map: map)
let json = map.JSON
map = Map(mappingType: .fromJSON, JSON: json)
mapping(map: map) // <<< ERROR
}
}
但我有错误
无法对不可变值使用变异成员:'self'不可变
我该如何解决这个问题,对于默认的imp。如果我将代码从扩展复制/粘贴到每个类,它的效果很好,但我需要默认imp。任何解决方案
答
您正在从非变异方法调用变异方法。为了transferToResponceAction
拨打mapping
,它也必须标记为mutating
。
答
这可能有助于
public protocol BaseMappable : class {
/// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process.
func mapping(map: Map)
}
另一种方法是从
public protocol DtoResponseRequestActionable {
mutating func transferToResponceAction(_ dto: TransferToResponce)
}
删除类,并添加突变为
mutating func transferToResponceAction(_ dto: TransferToResponce) {
+0
公共协议'BaseMappable'是来自框架**的**协议,我不能改变框架 –
'变异' 是不是有效的的方法类或类绑定的协议 –
Swift无法以这种方式处理混合类需求。您将需要将'class'要求移到'BaseMappable'。事实上,你已经标记了“Where Self:BaseMappable”并没有充分扩展“class-ness”。你必须标记这个函数'mutating'或从'mapping'中移除'mutating'。所以你必须删除'class'或扩展它。这不是出于深刻的故意原因。斯威夫特无法做到。 –
有关此错误的更多信息,请参阅https://www.bignerdranch.com/blog/protocol-oriented-problems-and-the-immutable-self-error/ –