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)

                }


        }

2 Answers 2

0
List {
    ForEach(self.allStations.dataStructure,id: \.id) { TubeLines in
        ForEach(TubeLines.lines, id: \.self) { line in
                    Text("\(line)")
                    .foregroundColor(Color.blue)
        }

        }
}

Like this?

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.