Search code examples
iosswiftapimodelalamofire

What is the use of Data Model while API Parsing in swift


Why we should use Data model while parsing API. whereas we can simply get response in the ViewController class it self.

Can someone tell me why we should use Data Model to parse api response..

Thanks in advance


Solution

  • Imagine that you have below json response from server after calling an API:

    {
    "settings": {
        "isUserActive": false,
        "isUserAdmin": false,
        "rollNumber": 10,
        "userId": 2,
        "userName": "John"
    },
    "status": 200,
    "message": "Success"
    }
    

    Now how will you access the value if you are not using data model. It will be like

    let name = response["settings"]["userName"] 
    

    (Assuming that you have converted the json into dictionary)

    1) What if you have to use the username at multiple place, then you have to do the same thing again.

    2) The above json response is simple so it will be easy to get a particular value, but imagine a json where there are nested objects, trying to retrieve a value manually can be pain.

    3) If you are working in a team there is a probability that some developers can misspell the key and it can take hours to debug.

    Using data model the compiler will throw error if the property is misspelled avoiding bugs.

    4) You will have to typecast every time you retrieve the data from dictionary.

    When using data models, need to do typecasting only once ie. when parsing the json.

    All this pain can be avoided simply using data model, you only have to parse the json once and you can simply use the key as property to access value.

    For example see the settings json, once you parse it to data model it can be used like this:

    let data = dataModel(json: jsonResponse)
    data.settings.userName // John
    data.settings.rollNumber //10
    data.status //200
    

    This is a good tool to convert the json in to data models Link

    Hope it helps.