9

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")

            }
        }
}
davidhu
  • 9,523
  • 6
  • 32
  • 53
sheeno12
  • 131
  • 1
  • 1
  • 4

2 Answers2

12

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
5

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.

funct7
  • 3,407
  • 2
  • 27
  • 33