我一直在尝试在下面的代码中实现 try 和 catch
if let s = songId {
let track: NSURL!
track = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(s, ofType: "mp3")!)
.............
}
我想出了以下代码:
do {
track = try NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(s, ofType: "mp3")!)
}
catch let error as NSError {
print("NSURL Error: \(error.localizedDescription)")
}
但我收到以下警告:
No calls to throwing functions occur within 'try' expression
和
'catch' block is unreachable because no errors are thrown in 'do' block
这对我来说很奇怪,因为这种结构通常有效。
只有使用 NSURL
时,这种结构才行得通。我不明白为什么会这样。也许这与它是可选的有关,但我不确定。
我不知道如何解决这个问题。我需要使用 try/catch 或类似的东西,但我不知道如何让它工作。
我在谷歌上看到了一些类似的问题,但没有给我答案。 所以我的问题是:如何使用 NSURL 实现 try/catch 构造或类似的东西?
提前致谢。
最佳答案
没有使用在定义中用 throws
关键字标记的方法。所以用 try-catch
包装你的代码真的没有多大意义。我建议考虑这一点:
let s = "song"
guard let trackURL = NSBundle.mainBundle().URLForResource(s, withExtension: "mp3") else {
print("File not found in the app bundle: \(s).mp3")
return false
}
有帮助吗?
关于ios - 尝试使用 NSUrl(fileURLWithPath) 捕捉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37570714/