
This tutorial has been updated to use Swift 3.0, Xcode 8, and Alamofire 4.1. Tapping on a row in the table view will open a detail view displaying additional data about that Star Wars species
Passing data from a table view to a detail view, using a storyboard & segue. Parsing JSON including arrays, strings to arrays and strings to dates (using a DateFormatter). Today we’ll keep progressing on this app to add more of the features required in “real” apps. Loaded more results as the user scrolled down in the table view. Parsed some string fields in the web service JSON. Turned the JSON response into an array of Swift objects. Pulled Star Wars species data from the Star Wars API using Alamofire. Let task = (with: url) ).ĬodingKey protocol defines how properties of a struct / object are linked to its encoded form (eg: JSON). We can then parse this JSON into Car struct like this: let url = URL(string: "")! Notice the struct conforms to the Decodable protocol, so that JSON can be converted into this struct instance.
Lets start with a simple Car struct like this : struct Car: Decodable
Parse JSON key into different property name. Parse JSON into array of structs / objects. In this post we will look into how to use the Decodable protocol to parse JSON into Object / Struct, parse struct / object into JSON and various scenario of parsing. Let car = try? JSONDecoder().decode(Car.self, from: jsonData)Ĭodable protocol is a combination of Encodable + Decodable, an object / struct conforming to Codable protocol can be converted from and to JSON. Let encodedJSONData = try? JSONEncoder().encode(car)Īn object / struct that conforms to Decodable protocol can be converted from JSON, like this : Bless Apple for introducing the Decodable, Encodable, Codable protocol in Swift 4, it makes life as an iOS developer easier phew.Īn object / struct that conforms to Encodable protocol can be converted to JSON, like this :