very new to SwiftUI and I've managed to learn a lot in very little time. The one thing I'm struggling with is displaying an array from a JSON file using a loop. I would love if someone can help me out with this!
Sorry if this is a super n00b question, I've searched a lot and I just can't seem to find any examples or answers to how to display this (or I'm possibly trying the wrong things)
Here is a sample of my JSON object
{
"name": "Name of Spot",
"city": "City of Spot",
"state": "State of Spot",
"id": 1001,
"description": "Description of Spot",
"imageName": "imageName",
"categories": [
{
"category": "Category Name 1"
},
{
"category": "Category Name 2"
},
{
"category": "Category Name 3"
}
]
}
Here is my current data model
struct Spot: Hashable, Codable, Identifiable {
var id: Int
var name: String
fileprivate var imageName: String
var city: String
var state: String
var description: String
What I would like to do is create a loop that displays a Text string of each of the Categories. I can't figure out how to add the array to my struct or how to create the loop that will display them. I've managed to create loops to get each of the "spots" and dynamically pull in the rest of the info, just not the categories.
Thanks in advance!
Edited: Here is an example of where I am getting the error
struct TestArray: View {
var spot: Spot
var body: some View {
VStack {
spot.categories.forEach { (category) in
Text(category["category"] ?? "n/a")
}
}
}
}
Spotobject?let spotData: [Spot] = load("spotData.json")JSONDecoderand decoding into yourSpotstruct. I'm guessing yourloadmethod is doing that and if so, the answer I posted should work. In the future, you should try to post a minimal example of your code, it's a lot more difficult to give you the proper answer when it's not the complete code and assumptions have to be made in how you're implementing other parts.