Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class "ViewController' has no initializers [duplicate]

Tags:

swift

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

            }
        }
}
like image 471
sheeno12 Avatar asked Oct 10 '16 23:10

sheeno12


People also ask

Has no initializers Swift?

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.

How do you initialize a class in Swift?

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 ... } }


2 Answers

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.

like image 187
funct7 Avatar answered Oct 24 '22 01:10

funct7


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.

like image 41
matt Avatar answered Oct 24 '22 00:10

matt