类协议:不能在不可变值上使用变异成员:' self'是不可改变的

时间:2017-07-31 23:55:31

标签: swift protocols swift-protocols

我有来自框架的协议

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
    }

}

但我有错误

  

不能在不可变值上使用变异成员:&#39; self&#39;是不可改变的

我如何修复它,默认为imp。如果我将代码从扩展名复制/粘贴到每个类,它运行良好,但我需要默认的imp。有解决方案吗

2 个答案:

答案 0 :(得分:2)

这可能会有所帮助

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) {

答案 1 :(得分:1)

您正在使用非变异方法调用变异方法。要transferToResponceAction拨打mapping,还必须将其标记为mutating