initializer for conditional binding must have optional type not AVAudioPlayer

时间:2021-02-03 17:05:42

    if let buttonBeep = self.setupAudioPlayerWithFile("ButtonTap", type: "wav") {
            
            self.buttonBeep = buttonBeep
        }
        if let secondBeep = self.setupAudioPlayerWithFile("SecondBeep", type: "wav") {
           
            self.secondBeep = secondBeep
        }
        if let backgroundMusic = self.setupAudioPlayerWithFile("HallOfTheMountainKing", type: "mp3") {
            
            self.backgroundMusic = backgroundMusic
        }

这样写就报错了initializer for conditional binding must have optional type not AVAudioPlayer。

最后将代码改为:

  if let buttonBeep: AnyObject = self.setupAudioPlayerWithFile("ButtonTap", type: "wav") {
            
            self.buttonBeep = buttonBeep as? AVAudioPlayer
        }
        if let secondBeep:AnyObject = self.setupAudioPlayerWithFile("SecondBeep", type: "wav") {
           
            self.secondBeep = secondBeep as? AVAudioPlayer
        }
        if let backgroundMusic:AnyObject = self.setupAudioPlayerWithFile("HallOfTheMountainKing", type: "mp3") {
            
            self.backgroundMusic = backgroundMusic as? AVAudioPlayer
        }

就没有问题了。