2017-02-25 22 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

相關問題