jsonswiftswift3objectmappergeneralization

Generalizing a function to map JSON to Object using ObjectMapper and swift 3


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)

Solution

  • 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>).