Swift SwiftUI iOS – Cannot convert value of type 'Binding<AVPlayer?>' to expected argument type 'Binding<AVPlayer>

struct LePlay: View {

    var fileName: String
    
    init(fileName: String) {
        self.fileName = fileName
    }
    
    @State var player: AVPlayer? = nil

    @State var isplaying = false
    @State var showcontrols = true
    @State var value : Float = 0
        
    var body: some View {
        
        ZStack{
            if(player != nil){
                CustomVideoPlayer(player: self.$player, isplaying: $isplaying)
                    .frame(width: 777, height: 777, alignment: .center)

                
                if(self.showcontrols){
                    Controls(player: self.$player, isplaying: self.$isplaying, pannel: self.$showcontrols, value: self.$value, memeHeight: 777, fileName: fileName)
                }
            }
        }
        .onAppear(){
            player = AVPlayer(url: URL(string: fileName)!)
        }
    }
}

I get:

Cannot convert value of type 'Binding<AVPlayer?>' to expected argument type 'Binding<AVPlayer>'

Why do I still get this error despite having if(player != nil){} ?

Adding ! like self.$player! also doesn’t solve the problem!

I tried to do just var player = AVPlayer(url: URL(string: fileName)!) right at the beginning but it doesn’t work.

Nothing basic just works in this horrendous garbage language, it’s disgusting and unintuitive. I’m getting sick and tired of swift.

>Solution :

What you are doing still doesn’t change what player is.

Take a look at this example…

let a: String? = "Hello, world!"

// The type of a is Optional<String> (aka String?)

if a != nil {
  // this code will run because a is not nil
  // but the type of a is still Optional<String>
}

To fix your code you can use optional binding…

let a: String? = "Hello, world!"

// The type of a is Optional<String> (aka String?)

if let a {
  // this code will run because a is not nil
  // and now the type of a inside this block is String and no longer Optional
}

Leave a Reply