如果我写“try”而不写“!”,我会尝试用Swift 2.0播放声音。我得到了错误“抛出的错误没有处理”,AVAudioPlayer不是可选的为什么Xcode请求'try!‘如果我写“尝试!”我的应用程序崩溃“在解包可选值时意外发现nil”
class TouchViewController: UIViewController {
var soundPath:NSURL?
...................
//Play Bipsound
do { soundPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Bipsound", ofType: "wav")!)
var sound = try! AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint: nil)
sound.prepareToPlay()
sound.play() }发布于 2015-09-29 07:42:45
var soundPath:NSURL?
if let path = Bundle.main.path(forResource: "Bipsound", ofType: "wav") {
soundPath = NSURL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint:nil)
sound.prepareToPlay()
sound.play()
} catch {
//Handle the error
}
}发布于 2015-09-29 07:49:37
假装你以前从未见过Swift中的!强制解包操作符,并完全停止使用它。它基本上就是“如果这个可选的包含nil,就会崩溃”操作符。使用"if let“样式的可选绑定或try/catch,就像@LLooggaann在他的优秀答案中所概述的那样。(已投票)
https://stackoverflow.com/questions/32832976
复制相似问题