2

I´m developing a project in Swift 3 using ObjectMapper and I have a lot of functions using the same code.

The function which does the conversion is this:

    func convertCategories (response:[[String : Any]]) {

    let jsonResponse = Mapper<Category>().mapArray(JSONArray: response )

    for item in jsonResponse!{
        print(item)
        let realm = try! Realm()
        try! realm.write {
            realm.add(item)
        }
    }

}

And I want to pass Category (Mapper) as an argument, so I can pass any type of Class Types to the function and use only one function to do the job, it would look like this:

    func convertObjects (response:[[String : Any]], type: Type) {

    let jsonResponse = Mapper<Type>().mapArray(JSONArray: response )

...

I´ve tried a lot of thinks but without result, ¿Can anyone help me achieving this?

Edited: For all with the same problem, the solution is this:

    func convertObjects <Type: BaseMappable> (response:[[String : Any]], type: Type)
{
    let jsonResponse = Mapper<Type>().mapArray(JSONArray: response )



    for item in jsonResponse!{
        print(item)
        let realm = try! Realm()
        try! realm.write {
            realm.add(item as! Object)
        }
    }


}

And to call the function is:

self.convertObjects(response: json["response"] as! [[String : Any]], type: type)

1 Answers1

2

I suspect you're just having a syntax issue here. What you mean is something like:

func convertObjects<Type: BaseMappable>(response:[[String : Any]], type: Type)

You can also write it this way (which is sometimes more readable, particularly when things get complicated):

func convertObjects<Type>(response:[[String : Any]], type: Type)
    where Type: BaseMappable {

You'd typically call it as:

convertObjects(response: response, type: Category.self)

The point is that convertObjects needs to be specialized over each type you want to convert, and that requires declaring a type parameter (<Type>).

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Thanks for your quick reply, @Rob How can I use the parameter inside the function and also conform to BaseMappable protocol? func convertCategories (response:[[String : Any]], type: Type) { let jsonResponse = Mapper().mapArray(JSONArray: response ) .... I have an error saying that Type is not conforming to BaseMappable protocol – Joaquin Sainz de la Maza Nov 06 '17 at 13:39
  • If you require a conformance, include it as a requirement of the type parameter (`: BaseMappable`). – Rob Napier Nov 06 '17 at 13:53