AVAudioPlayer不再使用Swift 2.0 / Xcode 7 beta [英] AVAudioPlayer no longer working in Swift 2.0 / Xcode 7 beta
问题描述
对于我的iPhone应用中的 var testAudio
声明,我在此处收到错误
For the var testAudio
declaration in my iPhone app, I am receiving an error here
来电可以抛出,但错误不能抛出属性初始化程序
"Call can throw, but errors cannot be thrown out of a property initializer"
import UIKit
import AVFoundation
class ViewController: UIViewController {
var testAudio = AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource("testAudio", ofType: "wav")!), fileTypeHint:nil)
当我搬到Xcode 7测试版时,就发生了这种情况。
This happened when I moved to the Xcode 7 beta.
如何我可以在Swift 2.0中使用这个音频剪辑吗?
How can I get this audio clip functioning in Swift 2.0?
推荐答案
Swift 2有一个全新的错误处理系统,你可以阅读更多关于它: Swift 2错误处理。
Swift 2 has a brand new error handling system, you can read more about it here: Swift 2 Error Handling.
在您的情况下, AVAudioPlayer
构造函数ca n抛出错误。 Swift不会让你使用在属性初始化器中抛出错误的方法,因为没有办法在那里处理它们。相反,在视图控制器的 init
之前不要初始化属性。
In your case, the AVAudioPlayer
constructor can throw an error. Swift won't let you use methods that throw errors in property initializers because there is no way to handle them there. Instead, don't initialize the property until the init
of the view controller.
var testAudio:AVAudioPlayer;
init() {
do {
try testAudio = AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource("testAudio", ofType: "wav")!), fileTypeHint:nil)
} catch {
//Handle the error
}
}
这使您有机会处理创建音频播放器时可能出现的任何错误,并会阻止Xcode向您发出警告。
This gives you a chance to handle any errors that may come up when creating the audio player and will stop Xcode giving you warnings.
这篇关于AVAudioPlayer不再使用Swift 2.0 / Xcode 7 beta的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!