Hello, I've completed the Landmarks App Apple Developer tutorial, since finishing it I decided to create a project using the .JSON code from the project.
I've wrote the code in an identical layout as the tutorial, however I am receiving the error - Couldn't parse lesssonData.json as array <Lesson> - when trying to load a preview and the app builds successfully but crashes when I launch it.
Below is the code, any help is appreciated!
LessonList.swift
import SwiftUI
struct LessonList: View {
var lesson: Lesson
var body: some View {
VStack {
List {
Section {
ForEach(lessons, id: \.self) { lesson in
Label(lesson.name, systemImage: "house")
}
}
Section {
Label("Hello World!", systemImage: "globe")
}
}
}
}
}
struct LessonList_Previews: PreviewProvider {
static var lessons = ModelData().lessons
static var previews: some View {
LessonList(lesson: lessons[0])
}
}
ModelData.swift
import Foundation
import Combine
final class ModelData: ObservableObject {
@Published var lessons: [Lesson] = load("lessonData.json")
}
var lessons: [Lesson] = load("lessonData.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)") // Error on this Line
}
}
lessonData.JSON
[
{
"id":"1001",
"lessonNo":"Lesson 1",
"name":"Introduction to Photography",
"category":"Introduction",
},
{
"id":"1002",
"lessonNo":"Lesson 2",
"name":"Negative and Positive Space",
"category":"Introduction",
},
{
"id":"1003",
"lessonNo":"Lesson 3",
"name":"Introduction to Camera Angles",
"category":"Introduction",
},
{
"id":"1004",
"lessonNo":"Lesson 4",
"name":"Lighting and Framing",
"category":"Beginners",
},
{
"id":"1005",
"lessonNo":"Lesson 5",
"name":"Still Photography",
"category":"Beginners",
},
{
"id":"1006",
"lessonNo":"Lesson 6",
"name":"Motion Photograhy",
"category":"Beginners",
},
{
"id":"1007",
"lessonNo":"Lesson 7",
"name":"Aperture and F-Stops",
"category":"Intermiediate",
},
{
"id":"1008",
"lessonNo":"Lesson 8",
"name":"Shutter Speeds",
"category":"Intermiediate",
},
{
"id":"1009",
"lessonNo":"Lesson 9",
"name":"Advanced Framing",
"category":"Advanced",
},
{
"id":"1010",
"lessonNo":"Lesson 10",
"name":"Advanced Aperture, F-Stops and Shutter Speeds",
"category":"Advanced",
},
]