Class Protocol: Cannot use mutating member on immutable value: 'self' is immutable

落花浮王杯 提交于 2019-12-12 04:54:20

问题


I have protocol from framework

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

and i have my protocol with extension (default implementation)

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
    }

}

but i have error

Cannot use mutating member on immutable value: 'self' is immutable

How I can fix it, for default imp. If I copy/paste code from extension to every class, it works good, but I need default imp. Any solutions?


回答1:


This might help

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

The other way would be to remove class from

public protocol DtoResponseRequestActionable {
    mutating func transferToResponceAction(_ dto: TransferToResponce)
}

and add mutating to

mutating func transferToResponceAction(_ dto: TransferToResponce) {



回答2:


You're calling a mutating method from a non-mutating method. In order for transferToResponceAction to call mapping, it also must be marked mutating.



来源:https://stackoverflow.com/questions/45426974/class-protocol-cannot-use-mutating-member-on-immutable-value-self-is-immutab

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