Getting "Out of range error" in a preview SwiftUI

Viewed 67

I'm learning SwiftUI and are mapping my app, but I'm having an error with one of the previews.

Hope you can help me figure it out.

Here is my model:

import Foundation

class RecipeModel: ObservableObject {
    
    @Published var recipes = [Recipe]()
    
    init() {
        
        // Parse local included json data
        getLocalData()
        
        // Download remote json file and parse data
        getRemoteData()
    }

Then I have this on Main

import SwiftUI

@main
struct ReallyMexican: App {
    var body: some Scene {
        WindowGroup {
            HomeView()
                .environmentObject(RecipeModel())
        }
    }
}

And this on the view I'm getting the error:

import SwiftUI

struct RecipeSearchView: View {
    
    var recipe:Recipe
    @EnvironmentObject var model: RecipeModel
    
    var body: some View {
        
        VStack {
            
            HStack {
                Image(recipe.image)
                    .resizable()
                    .scaledToFit()
                Text(recipe.name)
            }
        }
        .padding()
        
    }
}

struct RecipeSearchView_Previews: PreviewProvider {
    static var previews: some View {
        
        let model = RecipeModel()
            
            RecipeSearchView(recipe: model.recipes[0])
            
    }
}

And I use that view here:


import SwiftUI

struct SearchView: View {
    
    @EnvironmentObject var model: RecipeModel
    
    var body: some View {
        
        VStack (alignment: .leading){
           
            Text("Hello")
            
            NavigationView{
                List {
                    ForEach(model.recipes) { item in
                        RecipeSearchView(recipe: item)
                    }
                }
            }
        }
        .padding()
    }
}

struct SearchView_Previews: PreviewProvider {
    static var previews: some View {
        SearchView()
            .environmentObject(RecipeModel())
    }
}

The project Build Successfully and I can run it in the simulator.

But on the RecipeSearchView, I'm getting this error:, can't figure out why ‍♂️

"App Crash due to Our of Range Index”

Thanks in advance

0 Answers
Related