AVPlayerItem Swift 2 无检查
AVPlayerItem Swift 2 Nil Checking
代码在 Swift 1.2 中运行良好,但是当我更改 Xcode 7 (Swift 2) 时,出现错误,如下所示 if
语句。
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'
那么,我如何检查 AVPlayerItem
实际上是 Nil
?
您可以声明一个可选的:
let objFirstSound : AVPlayerItem? = AVPlayerItem(URL:NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(self.objVowels?.main_sound, ofType: "mp3") ?? ""))
然后做:
if let objFirstSound = objFirstSound
{
arrTemp.append(objFirstSound)
}
代码在 Swift 1.2 中运行良好,但是当我更改 Xcode 7 (Swift 2) 时,出现错误,如下所示 if
语句。
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'
那么,我如何检查 AVPlayerItem
实际上是 Nil
?
您可以声明一个可选的:
let objFirstSound : AVPlayerItem? = AVPlayerItem(URL:NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(self.objVowels?.main_sound, ofType: "mp3") ?? ""))
然后做:
if let objFirstSound = objFirstSound
{
arrTemp.append(objFirstSound)
}