How to write own model mapper in Swift Language

痞子三分冷 提交于 2020-01-07 08:26:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/43700443/how-to-write-own-model-mapper-in-swift-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!