-1
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

Eduard Unruh
  • 985
  • 1
  • 14
  • 35

1 Answers1

-1

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

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • You should be able to just do it without `_` and `State(wrappedValue:)` as of Xcode 14 at least. Though I still don't see why you would ever need an `AVPlayer` to be a `@State`. As Ashley states here, doesn't really make sense to use a `class` as a `State`. – shim Jan 18 '23 at 00:49