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)