1

I have a JSON file which I have imported. All records in the json file have an item which is an array consisting of between 1 and 3 items. This is causing the list to fail as there are some records which have a single entry and other records can have 2 or 3. When I specifically reference element 0, the app runs, but if I go to element 2 or 3, the app expectedly crashes. Is there a way I can get app to ignore nil values and run through. Sample of JSON File

[  
    {
        "id": 1,
       "tla":"ABR",
       "name":"Abbey Road",
       "lines": ["Dockland Light"]
    },
    {
       "id": 2,
       "tla":"ACT",
       "name":"Acton Town",
       "lines": ["District", "Piccadilly"]
    },
    {
       "id": 3,
       "tla":"ALD",
       "name":"Aldgate",
       "lines": ["Hammersmith", "Metropolitan"]
    }
]

The goal is to list all lines regardless if lines consist of 1, 2 or 3

List {


                ForEach(self.allStations.dataStructure,id: \.id) { TubeLines in


                    Text("\(TubeLines.lines[0])")
                    .foregroundColor(Color.blue)

                }


        }
guest
  • 2,185
  • 3
  • 23
  • 46
ufookoro
  • 337
  • 1
  • 4
  • 12

2 Answers2

0

I would use the ForEach loop with an index and count the elements of each array. Hard coding array indices is just asking for trouble. Something like this might work:

ForEach(0..<array.count) { i in
      Text("\(self.array[i])")
        .foregroundColor(Color.blue)
    }

I pulled this from this answer here Get index in ForEach in SwiftUI

flite3
  • 13
  • 3
  • The second answer was able to produce the result (lines) the first one error in that an identifiable was required. I put one in but got this error Instance method 'appendInterpolation' requires that '[String]' conform to '_FormatSpecifiable' – ufookoro Feb 04 '20 at 06:01
0
List {
    ForEach(self.allStations.dataStructure,id: \.id) { TubeLines in
        ForEach(TubeLines.lines, id: \.self) { line in
                    Text("\(line)")
                    .foregroundColor(Color.blue)
        }

        }
}

Like this?

Watermamal
  • 357
  • 3
  • 12