Browse Month: February 2018

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!
           }//struct

 

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 {
            print(err.localizedDescription)
        }

🤩 🌟 👏🏻   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 {
            print(err.localizedDescription)
        }
where,
        let data : Data = try! Data.init(contentsOf: fileUrl)
        var countryArray = [Country]()


Thank You !!!


Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at info@nanostuffs.com, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box