我按照教程回复:how to create an MP3 Player in Swift我遇到了 Swift 1.2 和 Swift 2.0 之间语法发生变化的地方。
我遇到了以下方法的错误处理问题:
player = AVAudioPlayer(contentsOfURL: url, error: &error)
我知道我需要使用 try
和 catch
来“Swift2-ify”它。我已经完成了 Swift 1.2 代码的“从苹果到橘子”的翻译,但我很难将其翻译成“从苹果到苹果”。
以下是 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()
}
}
我的翻译有什么错误吗?
最佳答案
你不再需要 var error: NSError?
,删除它和相关的行。
现在您在 catch
block 中处理可能的错误。
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
}
}
请注意,catch
block 中的这个 error
变量不是与之前相同的变量,它是一个新变量(类型为 ErrorType
) 由 catch
block 生成。
catch
block 还有另一种语法:
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
。
关于ios - AVAudioPlayer 的 contentsOfURL 错误处理 :error: in Swift 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33239107/