SwiftUI problem with displaying values from array using MVVM pattern

Viewed 124

I am new to swift and iOS development and i am having troubles with displaying values that i get from json file on to the iPhone screen.

Model code:

import Foundation

struct JSONModel: Codable{
    var name: String
    var value: String
}

ViewModel code:

import Foundation

class JSONViewModel: ObservableObject{
    @Published var resultArray: [JSONModel] = []
    
    init(){
        parseJSON()
    }
    
    func parseJSON(){
        var result: [JSONModel] = [] //empty array
        guard let url = Bundle.main.url(forResource:"animals", withExtension: "json") else { return }
        
        do{
            let jsonData = try Data(contentsOf: url)
            result = try JSONDecoder().decode([JSONModel].self, from: jsonData)
            
            DispatchQueue.main.async {
                self.resultArray = result
            }
        }
        catch{
            print("Error: \(error)")
        }
    }  
}

ContentView code:

import SwiftUI

struct ContentView: View {
    @StateObject var viewModel = JSONViewModel()
            
    var body: some View {
        NavigationView {
            ScrollView {
                ForEach(viewModel.resultArray){ item in
                    Text(item.name)
                }
            }
        }
    }
}

I do not get any specific error the only thing Xcode shows me is this:

Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project

Any help would be much appreciated

1 Answers

Conform your model to Hashable and use .self to identify it:

struct JSONModel: Codable, Hashable{
    var name: String
    var value: String
}



ForEach(viewModel.resultArray, id:\.self){ item in
                    Text(item.name)
                }
Related