Objectmapper: Implement Mappable in an extension

Created on 27 Oct 2015  路  10Comments  路  Source: tristanhimmelman/ObjectMapper

I'd like to use ObjectMapper with some classes that I do not control, so I'd have to implement the Mappable protocol from an extension, which is currently impossible because of the required init? method.

If I try to implement init?(map: Map) from an extension the compiler gives me this error:

initializer requirement 'init' can only be satisfied by a `required` initializer in the definition of non-final class 'ClassName'

How could I make it work? I saw that ObjectMapper used to have a newInstance(map: Map) method. I'd have been able to use that, since it doesn't involve the restrictions on required init()s.

enhancement

Most helpful comment

Except those aren't _my_ classes so I can't change them at all. I've edited ObjectMapper to use the old newInstance(map: Map) method, but it still doesn't work like I'd want it to.

Using newInstance I'm able to add Mappable conformance to the classes I need, but since Swift doesn't allow me to override methods in an extension I can't implement Mappable in class clusters.

All 10 comments

Try to mark your class as final and use convenience init? in the extension.

Except those aren't _my_ classes so I can't change them at all. I've edited ObjectMapper to use the old newInstance(map: Map) method, but it still doesn't work like I'd want it to.

Using newInstance I'm able to add Mappable conformance to the classes I need, but since Swift doesn't allow me to override methods in an extension I can't implement Mappable in class clusters.

I also experienced same issue with other serializers like Cereal That is why I stopped using them. I currently use some kind of proxy class to get data from original class to proxy class and then use swift-serializer to turn object to JSON or dictionary. It doesn't support structs or have all advanced properties of mentioned libraries but it works for me.

I think your issue can probably relate to #260

+1.

+1

+1

+1 and current protocol Mappable creates some issue with Realm. I need it on extension, so I've create another "map" from that copies models with Mappable protocol to Realm model and back to network object.

This would be a nice addition but I see no simple way to get rid of the init? function. I am marking this as an enhancement to keep track of the idea

I have just released v1.5.0 which now supports implementing ObjectMapper within an extension. If you wish to do this, please use the StaticMappable protocol. With this update StaticMappable no longer requires the init?(_ map: Map) function which was causing difficulties.

Hope this helps you all

Was this page helpful?
0 / 5 - 0 ratings