Decodable in Swift 4

According to Apple Codable is “A type that can convert itself into and out of an external representation.”

  1. Encodable — for encoding
  2. Decodable — for decoding
  3. Codable — for both encoding as well as decoding

Let suppose we need to decode json response of type as below,

               "name": "India",
               "dial_code": "+91",
               "code": "IN"

For Parsing purpose  we generally create model class or struct or enum for now lets create struct for country name , dial code and country code as below,.

           struct Country: Decodable {
                  let name: String!
                  let dial_code: String!
                  let code: String!


Here if you observer🧐 we have confirm Decodable protocol to struct. Let move to next step as 🤞🏻🤞🏻PARSING Phase  🤞🏻🤞🏻 as below,.

        do {
            countryArray = try JSONDecoder().decode(Country.self, from: data)
        } catch let err {

🤩 🌟 👏🏻   PARSING is successful…….💐💐💐💐💐😅

Now lets parse array😱 of country 🤨. No worry it is so easy to do. You have to make Country as a array.

        do {
            countryArray = try JSONDecoder().decode([Country].self, from: data)
        } catch let err {
        let data : Data = try! Data.init(contentsOf: fileUrl)
        var countryArray = [Country]()

Thank You !!!