-1

I have a requirement for mapping values coming from service layer to the UI key values. Let's say two values are coming from the service layer in array of dictionary

{
    ["identifier": "1", "fullname": "Bob Steve"]
}

I have to modify the key in my side identifier to become id & fullname to become name. How to write a model mapper to do so. Can anyone guide me how to write a model mapper.

There are lot of third party model mapper available, but I want to write my own.

Thanks in advance.

Rashwan L
  • 38,237
  • 7
  • 103
  • 107

1 Answers1

2

You could do it something like this:

class Mapper {
    // Singel object
    func person(obj: [String: Any]) -> Person {
        guard let identifier = obj["identifier"] as? String, let fullname = obj["fullname"] as? String else { return ...}

        let person = Person(identifier: identifier, fullname: fullname)
        return person
    }

    // Dictionary
    func persons(dictionary: [[String: Any]]) -> [Person] {
        for obj in dictionary {
            let person = person(obj)
            persons.append(person);
        }
        return persons
    }
}

Assuming you have a Person class for instance.

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • why you not using `struct` would you tell me please – Nazmul Hasan Apr 29 '17 at 21:25
  • @NazmulHasan, I assume that OP has a lot of values that he will be using therefore class. So basically it really depends on how many values OP is storing and the size / structure of them. If it´s only two like he has in the post then sure go with struct. – Rashwan L Apr 29 '17 at 21:28
  • Thanks all for the solution. I just wanted to write my own model mapper. It was also for the learning purpose. Yes third party mapper are available but wanted to use my own. – Raghunath Sahoo May 02 '17 at 08:20
  • @RaghunathSahoo, if my answer was useful, click the upvote button to the left of it. If it answered your question, click the checkmark to accept it. That way others know that you've been (sufficiently) helped. – Rashwan L May 27 '17 at 09:00