I am new to swift and I have built a simple ui off an example that I had typed out and knew to be working, but when I substitute my own data and write my own model it breaks down.
I have linted my JSON and it is valid. My UI throws an error Value of type 'Resorts' has no member 'items'. The trouble I am having is looping through the json objects with a ForEach and displaying items.resortName
Any help would be HUGE!
Here is my code:
ContentModel
import Foundation
class DataModel: ObservableObject {
@Published var resorts = [Resorts]()
init() {
getLocalData()
}
func getLocalData() {
// Get a url to the json file
let jsonUrl = Bundle.main.url(forResource: "data", withExtension: "json")
do {
// Read the file into a data object
let jsonData = try Data(contentsOf: jsonUrl!)
// Try to decode the json into an array of modules
let jsonDecoder = JSONDecoder()
let resorts = try jsonDecoder.decode([Resorts].self, from: jsonData)
// Assign parsed modules to modules property
self.resorts = resorts
}
catch {
// TODO log error
print("Couldn't parse local data \(error)")
}
}
}
Resorts
import Foundation
struct Resorts: Decodable, Identifiable {
var id: Int
var apiVersion: String
var region: Region
}
struct Region: Decodable, Identifiable {
var id: Int
var name: String
var items: [Items]
}
struct Items: Decodable, Identifiable {
var id: Int
var resortName: String
var state: String
}
JSON Snippet
[
{
"id":0,
"apiVersion": "12.2",
"region": {
"id": 0,
"name": "Rocky Mountains",
"items": [
{
"id": 0,
"resortName": "A Basin",
"state": "Colorado",
"reportDateTime": "2021-06-05 06:25:00",
"resortStatus": "minutes",
"operationStatus": "8",
...
Content View
struct ContentView: View {
@EnvironmentObject var model: DataModel
var body: some View {
Text("Hello")
ScrollView {
HStack {
ForEach(model.resorts) { resort in
ZStack {
Color.white
.cornerRadius(8)
VStack {
Text("Resort by name")
// Text(resort.items)
}
}
.frame(width: 175, height: 100)
.shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 0)
}
}
}
}
}