As you see, in the struct ContentView, you have a declaration of an instance property named astronautsJson, and its initial value (in other words, property initializer) is decode("astronauts.json").
can someone tell me y it happens and how to fix this?
As the error message is clearly stating,
In Swift, you cannot use instance members (neither methods nor properties) within property initializer.
You are trying to use the instance member (in your case, method) decode(_:), so Swift compiler is telling you you cannot.
Using an extension (of other type than ContentView) would be a preferable way, but there may be other ways.
One way is making your decode a type member (static method):
struct ContentView: View {
let astronautsJson: [Astronaut] = decode("astronauts.json")
var body: some View {
Text("\(astronautsJson.count)")
.padding()
}
static func decode(_ file: String) - [Astronaut] {
guard let url = Bundle.main.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([Astronaut].self, from: data) else {
fatalError("Failed to decode \(file) from bundle.")
}
return loaded
}
}
By the way, using try? with guard-let is not recommended. You should better find a better video:
static func decode(_ file: String) - [Astronaut] {
guard let url = Bundle.main.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle.")
}
let data: Data
do {
data = try Data(contentsOf: url)
} catch {
fatalError("Failed to load \(file) from bundle with error: \(error)")
}
let decoder = JSONDecoder()
let loaded: [Astronaut]
do {
loaded = try decoder.decode([Astronaut].self, from: data)
} catch {
fatalError("Failed to decode \(file) from bundle with error: \(error)")
}
return loaded
}
Using do-catch with try (not try?) would make your code a little longer, but you can get more info in case of errors, which may help you finding what is causing the error.