class"ViewController"没有初始值设定项

she*_*o12 9 swift

我试图建立一个简单的声音应用程序.我想要一个按钮来播放一个非常像音板的剪辑.问题是,当我去构建它时,类"ViewController"没有初始化器

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

            }
        }
}
Run Code Online (Sandbox Code Playgroud)

mat*_*att 12

因为它没有初始化器.你有一个属性:

var audioPlayer: AVAudioPlayer
Run Code Online (Sandbox Code Playgroud)

...但你没有初始化它.当然,你有一个类型,但类型不是一个.所有属性都必须具有初始值.


fun*_*ct7 5

就像马特提到的那样,它正在发生,因为财产没有被初始化.

在Swift中,您必须为可能nil在任何时候使用的变量使用选项.您必须audioPlayer从头开始初始化或使用可选类型,包括隐式展开的可选项,如果您知道它将在稍后设置并保持这种方式.