Cannot preview in this file -- `fatalError` in ModelData.swift

that is also appearing when I click the "I" button in the preview error banner

I am attempting to use the SwiftUI tutorial at https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation (section 2)

here is the code for the view that the preview is "crashing" on:

import SwiftUI

struct LandmarkRow: View {

    var landmark: Landmark

    var body: some View {

        HStack {

            landmark.image

                .resizable()

                .frame(width: 50, height: 50)

            Text("landmark.name")

            

            Spacer()

        }

    }

}

struct LandmarkRow_Previews: PreviewProvider {

    static var previews: some View {

        LandmarkRow(landmark: landmarks[0])

    }

}

Here is the code for the area it is having the problem:

import Foundation

var landmarks: [Landmark] = load("landmarkDelta.json")

func load<T: Decodable>(_ filename: String) -> T {

    let data: Data

    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)

    else {

        fatalError("Couldn't find (filename) in main bundle.")

            

    }

    do {

        data = try Data(contentsOf: file)

    } catch {

        fatalError("Couldn't load (filename) from main bundle:\n(error)")

    }

    do {

        let decoder = JSONDecoder()

        return try decoder.decode(T.self, from: data)

    } catch {

        fatalError("Couldn't parse (filename) as (T.self):\n(error)")

    }

}

It is saying there is an error on line 17. Here is the line of code:

        fatalError("Couldn't find (filename) in main bundle.")

Here is the code from the Tutorial:

import Foundation

var landmarks: [Landmark] = load("landmarkData.json")

func load<T: Decodable>(_ filename: String) -> T { let data: Data

guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
    fatalError("Couldn't find \(filename) in main bundle.")
}

do {
    data = try Data(contentsOf: file)
} catch {
    fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}

do {
    let decoder = JSONDecoder()
    return try decoder.decode(T.self, from: data)
} catch {
    fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}

}

does anyone know what's wrong and how to fix it?

Please format code with code formatter (<>) to make it readable.

I got the same error.

In my case, there was something wrong in the landmarkDelta.json file, so replaced it with the landmarkDelta.json which I downloaded from the SwiftUI Tutorial site and it worked.

(I'm sorry if my English is not good enough to convey the message.)

Hi @mimats, Your solution is very helpful. I created a group and named it "Resources", after I added landmarkDelta.json which I downloaded from the SwiftUI Tutorial site to that Resources Group. its solved.

Cannot preview in this file -- &#96;fatalError&#96; in ModelData.swift
 
 
Q