How to use Alamofire with Codable in Swift?

Hello after long time I am writing this blog regarding use of Alamofire with Codable model object for the ease of MVC architecture.
Let’s rewind with some of the post which is used to cover this point:

  1. How to use Alamofire and SwiftyJSON with Swift?
  2. How to create a wrapper for Alamofire and SwiftyJSON?
  3. Use of Codable and Coding Key with JSONEncoder and JSONDecoder in Swift 4

Let see about use of Alamofire with Codable model object

Step 1 – Create Codable object based on JSON response.

Here I am taking an example of a web service which contains JSON related to the contact.

So, we can create two Codable files from this JSON as per hierarchy. These would be like as follows:

As you can see we have created 2 objects Contact and Phone. Here Phone is in sub hierarchy.

Step 2 – Let’s update AFWrapper

As we have previously revised blogs, there is a blog mentioned about to create a wrapper of the Alamofire and SwiftyJSON. We have to replace the SwiftyJSON code to return normal dictionary objects, and after that we will convert that dictionary to the Codable object.
So here I have updated the AFWrapper class file to do that thing:

Step 3 – Implement and convert the response in object

We will call a web service which contain that kind of JSON response. And after calling the web-service we will decode the object to create the Codable object.

In above sample I have added one text view in the view controller and I am fetching the data from the contacts API. After that using JSONSerialization and JSONDecoder we will get our decoded Contact object with Phone object.

Conclusion

Swift 4 comes with so many updates. We are going to have a great time exploring them all and finding out so much more by using it on further projects. We have learned about Codable and use of it. You too should go check it out and share your experiences with us in the comments section.
Hope you liked the article.
Happy Coding 🙂