Hello! Currently I'm decoding astronaut.json into contentView. I've followed along but I seem to get decoding error: "failed to decode..." in the decoding stage. A bit confused because as far as I know, I've copied all the code in from paul's video. Final output should be: ("(astronauts.count)"). Many thanks :)
import Foundation
struct Astronaut: Codable, Identifiable {
let id: String
let name: String
let description: String
}
import Foundation
extension Bundle {
func decode(_ file: String) -> [String: Astronaut] {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle.")
}
let decoder = JSONDecoder()
guard let loaded = try? decoder.decode([String: Astronaut].self, from: data) else {
fatalError("failed to decode \(file) from bundle.")
}
return loaded
}
}
import SwiftUI
struct ContentView: View {
let astronauts1 = Bundle.main.decode("astronauts.json")
var body: some View {
Text("\(astronauts1.count)")
.padding()
}
}
Example JSON
[
{
"id": "grissom",
"name": "Virgil I. \"Gus\" Grissom",
"description": "Virgil Ivan \"Gus\" Grissom (April 3, 1926 – January 27, 1967) was one of the seven original National Aeronautics and Space Administration's Project Mercury astronauts, and the first of the Mercury Seven to die. He was also a Project Gemini and an Apollo program astronaut. Grissom was the second American to fly in space, and the first member of the NASA Astronaut Corps to fly in space twice.\n\nIn addition, Grissom was a World War II and Korean War veteran, U.S. Air Force test pilot, and a mechanical engineer. He was a recipient of the Distinguished Flying Cross, and the Air Medal with an oak leaf cluster, a two-time recipient of the NASA Distinguished Service Medal, and, posthumously, the Congressional Space Medal of Honor."
}
]