Accessing Nested JSON Object with Decodable


#1

I’m trying to access goalsHomeTeam & goalsAwayTeam from result. But I’m not sure how it’s read when I decode FixtureResponse

struct FixturesResponse: Decodable {
  let fixtures: [Fixture]
}

Here is my Fixture model

struct Fixture: Decodable {  
  let date: String?
  let homeTeamName: String?
  let awayTeamName: String?
  let result: Result  
}

Result Model

struct Result: Decodable { 
  let goalsHomeTeam: Int?
  let goalsAwayTeam: Int?
}

FixtureTableViewController

  func fetchURL(url: String) {
    Alamofire.request(url).responseData { (response) in
      guard let data = response.data else { return }
      do {
        let decoder = JSONDecoder()
        let fixtureResponse = try decoder.decode(FixturesResponse.self, from: data)
        self.results = fixtureResponse.???? <--- confused here
        self.fixtures = fixtureResponse.fixtures
      }
      catch {
        print(error.localizedDescription)
      }
      self.tableView.reloadData()
    }
  }

#2

So if I read this correctly, you get to this line just fine:

let fixtureResponse = try decoder.decode(FixtureResponse.self, from: data)

??

If so, then to access to the result you have to enumerate all of the fixtures in order to get to the results.

If you want this flattened out (i.e. just get a list of the results and you don’t care about the wrapping stuff):

let results = fixtureResponse.fixtures.map { $0.result }

The type of results will be inferred by the compiler to be [Result].

If the map is confusing, it’s essentially the same as this:

var results = [Result]()
for fixture in fixtureResponse.fixtures {
   results.append(fixture.result)
}

But without the mutable array.

Does this make sense?


#3

Makes perfect sense. Thanks Ben!