Accessing Nested JSON Object with Decodable


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?


  func fetchURL(url: String) {
    Alamofire.request(url).responseData { (response) in
      guard let 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 {


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 = { $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 {

But without the mutable array.

Does this make sense?


Makes perfect sense. Thanks Ben!