According to Apple Codable is “A type that can convert itself into and out of an external representation.”
- Encodable — for encoding
- Decodable — for decoding
- 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 !!!