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 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your quick reply, @Rob How can I use the parameter inside the function and also conform to BaseMappable protocol? func convertCategories <Type> (response:[[String : Any]], type: Type) { let jsonResponse = Mapper<Type>().mapArray(JSONArray: response ) .... I have an error saying that Type is not conforming to BaseMappable protocol
If you require a conformance, include it as a requirement of the type parameter (: BaseMappable).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.