swiftswift2avfoundationxcode7avplayeritem

AVPlayerItem Swift 2 Nil Checking


The code was working fine in Swift 1.2 but when I changed the Xcode 7 (Swift 2), I am getting error, which is written below in if statement.

let objFirstSound = AVPlayerItem(URL:NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(self.objVowels?.main_sound, ofType: "mp3") ?? ""))

if objFirstSound != nil {
   arrTemp.append(objFirstSound)
}

Binary operator '!=' cannot be applied to operands of type 'AVPlayerItem' and 'NilLiteralConvertible'

So, how can I check AVPlayerItemis actually Nil?


Solution

  • You could declare an Optional:

    let objFirstSound : AVPlayerItem? = AVPlayerItem(URL:NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(self.objVowels?.main_sound, ofType: "mp3") ?? ""))
    

    Then do:

    if let objFirstSound = objFirstSound
    {
        arrTemp.append(objFirstSound)
    }