Reputation: 3
I want to load JSON file to swift playground in two type, but it seems a bit confusing because after adding the astronaout.json file (in the first line) it gives the error "top level statement cannot begin with a closure expression", I don't know how to fix it, 2.error is missions. json file (on line 3) 'consecutive statements on a line must be separated by ";".
Any idea how to fix that?
I can’t show the whole code of this files cuz it’s 369 line*
And here is the bundle-decodable code;
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
}
}
Upvotes: 0
Views: 711
Reputation: 51892
First you need to add your json files as resources and not source code files to the playground.
In the playground you access the files using the Bundle
class, there are several ways, one is
if let url = Bundle.main.url(forResource: "missions", withExtension: "json"),
let data = try? Data(contentsOf: url) {
// decode data object
}
Upvotes: 2