2017-02-25 19 views
-3

您好,在此先感谢您的帮助。我正在采取一个快速的udemy课程,我已经完成了5次代码,并将其与教练进行了比较,就我所知,它是相同的。我无法弄清楚为什么我的代码无法正常工作。它说“类”ViewController“没有初始化器”,我该如何解决这个问题? https://gyazo.com/1c9d0f5d8de70991aff353ac66505ab8swift中的多个错误,类未初始化,无法调用非函数类型的值'Bundle'

1 // ViewController.swift 
    2 // RetroCalculator 
    3 // 
    4 // Created by miles richie on 2/22/17. 
    5 // Copyright © 2017 Mit3ch. All rights reserved. 
    6 // 
    7 
    8 import UIKit 
    9 import AVFoundation 
    10 
    11 class ViewController: UIViewController { 
    12 
    13 var btnSound: AVAudioPlayer 
    14 
    15 override func viewDidLoad() { 
    16   super.viewDidLoad() 
    17   
    18  let path = Bundle.main.path(forResource: "btn", ofType: "wav") 
    19 let soundURL = URL(fileURLWithPath: path!) 
    20   
    21  do{ 
    22   try btnSound = AVAudioPlayer(contentsOf: soundURL) 
    23   btnSound.prepareToPlay() 
    24  } catch let err as NSError{ 
    25   print(err.debugDescription) 
    26  } 
    27 } 
    28  
    29  @IBAction func numberPressed(sender: UIButton) { 
    30    
    31  } 
    32  
    33  func playSound(){ 
    34   if btnSound.isPlaying{ 
    35    btnSound.stop() 
    36   } 
    37} 
    38} 
+7

请[编辑]你的问题并将相关代码粘贴到您的问题中。清楚地指出哪些线路导致问题并包含完整的错误消息。 – rmaddy

回答

0

发生此错误ViewController" has no initializers是因为btnSound被声明为非可选值而没有默认值。任何非可选项必须在init方法中初始化或具有默认值。

在你的情况申报财产作为inplicit解开可选

var btnSound: AVAudioPlayer! 

顺便说一句:有一个URL相关的API通过复制来获取URL直接

let soundURL = Bundle.main.url(forResource: "btn", withExtension: "wav") 
+0

非常感谢!祝你有个好的一天。 – alaskanguy

0

从main删除()。因此,您的代码将与let path = Bundle.main.path(forResource: "btn", ofType: "wav")

+0

非常感谢你的工作,如果它不麻烦,你能解释为什么工作?还有关于“ViewController没有初始化器”的任何想法? – alaskanguy

相关问题