SeanForReal
SeanForReal

Reputation: 141

SwiftUI - Displaying array from JSON file

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")
            }
        }

    }
}

Upvotes: 1

Views: 1157

Answers (1)

clawesome
clawesome

Reputation: 1319

You can make a Category object and declare categories as an array of that object. If you want to do it without making a new object that only has one property, you could also just use an array of Dictionaries with String as the key value.

struct Spot: Hashable, Codable, Identifiable {
    var id: Int
    var name: String
    fileprivate var imageName: String
    var city: String
    var state: String
    var description: String
    var categories: [Category]
}

struct Category: Codable {
    var category: String
}

If you want to use an array of Dictionaries instead:

struct Spot: Hashable, Codable, Identifiable {
    ...
    var categories: [[String: String]]
    ...
}

edit:

To iterate and display the categories from the array of Dictionaries, you should be able to do it something like this, assumming your Spot object is named spot:

VStack {
    spot.categories.forEach { (category) in
        Text(category["category"] ?? "n/a")
    }
}

Upvotes: 1

Related Questions