Im trying to build a simply sound app. I want a button press to play a clip pretty much like a soundboard. problem is when I go to build it says class "ViewController' has no initializers
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playSound(sender:UIButton){
// Set the sound file name & extention
let audioFilePath = Bundle.main.path(forResource: "emp_learntoknow", ofType: "mp3")
if audioFilePath != nil {
let audioFileUrl = URL.init(fileURLWithPath: audioFilePath!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: audioFileUrl)
audioPlayer.play()
} catch {
print("audio file is not found")
}
}
}
Every Swift developer runs into this error at some point. To resolve this error, you need to understand an important aspect of classes. Swift requires that the stored properties of a class receive an initial value during initialization.
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
Like Matt has mentioned, it's happening because the property is not initialized.
In Swift, you have to use optionals for variables that could be nil
at any point. You'll have to either initialize audioPlayer
from the beginning or use an optional type, including the implicitly unwrapped optional if you know it will be set later on and stay that way.
Because it has no initializers. You have a property:
var audioPlayer: AVAudioPlayer
...but you are not initializing it. You have, of course, given it a type, but a type is not a value. All properties must have initial values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With