Post

Replies

Boosts

Views

Activity

property initializers run before 'self' is available
hi i saw the tutorial named "Loading a specific kind of Codable data – Moonshot SwiftUI Tutorial 5/10" youtube.com/watch?v=PG_OHOEPx2I&ab_channel=PaulHudson and it worked perfectly, but when i tried to do the same thing only without the extension, i get this error "Cannot use instance member 'decode' within property initializer; property initializers run before 'self' is available". basically its the same code as on the internet only the function is written in different place (in content view and not inside the bundle extension)!!! can someone tell me y it happens and how to fix this? thx in advance. swift struct ContentView: View {       let astronautsJson: [Astronaut] = decode("astronauts.json")       var body: some View {     Text("\(astronautsJson.count)")       .padding()   }       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   }     }
7
0
3.5k
Apr ’21