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)
This happened when I moved to the Xcode 7 beta.
How can I get this audio clip functioning in Swift 2.0?
Swift 2 has a brand new error handling system, you can read more about it here: Swift 2 Error Handling.
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 theinit
of the view controller.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.