SwidtUI iOS – Cannot use instance member x within property initializer; property initializers run before 'self' is available

Advertisements
struct LePlay: View {

    var fileName: String
    
    init(fileName: String) {
        self.fileName = fileName
    }
    
    @State var player = AVPlayer(url: URL(string: "https://blala.com/?n=" + fileName)!)

I get

Cannot use instance member ‘fileName’ within property initializer; property initializers run before ‘self’ is available

in the last fileName in the code

I’ve already seen similar questions but none of the solutions there are working for me

>Solution :

You need to initialise player in your init, as follows:

struct LePlay: View {
    
    var fileName: String
    @State var player: AVPlayer

    init(fileName: String) {
        self.fileName = fileName
        _player = State(wrappedValue: AVPlayer(url: URL(string: "https://blala.com/?n=" + fileName)!))
    }
}

I’m not sure what will happen here, assigning a class to State.

You should wrap player in an ObservableObject class, which you can assign to a StateObject

Leave a Reply Cancel reply