错误处理AVAudioPlayer的contentsOfURL:错误:在Swift 2中

时间:2015-10-20 14:14:51

标签: ios swift swift2 avaudioplayer

我遵循了教程re:how to create an MP3 Player in Swift,我遇到了Swift 1.2和Swift 2.0之间语法发生变化的地方。

我遇到了以下方法的错误处理问题:

player = AVAudioPlayer(contentsOfURL: url, error: &error)

我知道我需要使用trycatch来" Swift2-ify"它。我做了一个"苹果到橘子"翻译Swift 1.2代码,但我很难做到#34;苹果到苹果"。

以下是 Swift 1.2 中教程的相关方法/声明。

var player: AVAudioPlayer?

func queueTrack(){
    if (player != nil) {
        player = nil
    }

    var error:NSError?
    let url = NSURL.fileURLWithPath(tracks[currentTrackIndex] as String)
    player = AVAudioPlayer(contentsOfURL: url, error: &error)

    if let hasError = error {
        //TODO: SHOW ALERT HERE
    } else {
        player?.delegate = self
        player?.prepareToPlay()
    }
}

以下是我在 Swift 2.0 中尝试的内容。它运行,但我收到警告。

func queueTrack() {
    if (player != nil) {
        player =  nil
    }

    let url = NSURL.fileURLWithPath(tracks[currentTrackIndex] as String)
    // I get a warning to make 'var error' to 'let error' here
    // If I do what the compiler says, I get a warning the error isn't
    // initialized after 'catch' outside the curly braces
    var error: NSError? // TODO: figure out how to remove this warning


    do {
        player = try AVAudioPlayer(contentsOfURL: url)
    } catch {
        NSLog("Unresolved error \(error)")
        // SHOW ALERT OR SOMETHING
    }

    // Immutable value 'hasError' was never used; consider replacing
    // with '_' or removing it
    // If earlier declaration of error is changed to let, the warning turns
    // into an compiler error

    if let hasError = error {
        // show alert
    } else {
        player?.delegate = self
        player?.prepareToPlay()
    }
}

我在翻译中犯了什么错误?

1 个答案:

答案 0 :(得分:2)

您不再需要var error: NSError? ,删除它和相关的行。

现在您处理catch块中的可能错误。

func queueTrack() {

    let url = NSURL.fileURLWithPath(tracks[currentTrackIndex] as String)

    do {
        player = try AVAudioPlayer(contentsOfURL: url)
        player?.delegate = self
        player?.prepareToPlay()
    } catch {
        NSLog("Unresolved error \(error)")
        // SHOW ALERT OR SOMETHING
    }

}

请注意,error块中的catch变量与以前相同的变量,它是由ErrorType生成的新变量(类型为catchcatch阻止。

do { player = try AVAudioPlayer(contentsOfURL: url) player?.delegate = self player?.prepareToPlay() } catch let error as NSError { NSLog("Unresolved error \(error.debugDescription)") // SHOW ALERT OR SOMETHING } 块还有另一种语法:

error

此处ErrorType不会像往常一样NSError而是$Properties = "Certificates, DisplayName, LastLogonTimeStamp, Enabled, extensionAttribute11" Get-ADUser -Filter {(LastLogonTimeStamp -gt (Get-Date).AddDays(-90)) -and enabled -eq $true)} -Properties $Properties | select $Properties | sort Certificates, extensionAttribute11 | Export-Csv file.csv