为什么Swift不让我把对象放在数组中

时间:2016-07-24 17:57:20

标签: ios arrays swift xcode

我试图创建一个数组,然后将对象放入其中,但它给了我一个错误

fatal error: unexpectedly found nil while unwrapping an Optional value

我的代码片段:

import UIKit
import HTPressableButton

class GameViewController: UIViewController {

  @IBOutlet weak var lblAnswer: UILabel!

  var firstOption:HTPressableButton!
  var secondOption:HTPressableButton!
  var thirdOption:HTPressableButton!
  var fourthOption:HTPressableButton!


  var optionButtons:[HTPressableButton] = []

    override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view.


      //Declaration of Width and Height to avoid calculate this value in each button.
      BUTTON_WIDTH = UIScreen.mainScreen().bounds.width-210;
      BUTTON_HEIGHT = UIScreen.mainScreen().bounds.width-240;


      optionButtons[0] = firstOption
      optionButtons[1] = secondOption
      optionButtons[2] = thirdOption
      optionButtons[3] = fourthOption

      lblAnswer.font = UIFont(name: lblAnswer.font.fontName, size: (lblAnswer.font?.pointSize)!)
    }

}

它停在optionButtons[0] = firstOption我试图改变它

optionButtons[0] = HTPressableButton(frame: firstFrameOp, buttonStyle: HTPressableButtonStyle.Rect)//firstOption

但它给了我一个不同的错误:fatal error: Index out of range

任何帮助?

2 个答案:

答案 0 :(得分:3)

崩溃的发生是因为您正试图访问不存在的数组中的索引。

您只需使用append(Element)将数组输入数组,或者将数组设置为:

optionButtons = [firstOption, secondOption, thirdOption, fourthOption]

答案 1 :(得分:1)

您只是以错误的方式初始化按钮。您创建了一个空数组,然后您尝试访问其中的项目,但它是空的。您必须创建按钮,然后将它们添加到阵列。 干杯:)

class GameViewController: UIViewController {

  @IBOutlet weak var lblAnswer: UILabel!

  var firstOption:HTPressableButton!
  var secondOption:HTPressableButton!
  var thirdOption:HTPressableButton!
  var fourthOption:HTPressableButton!


  var optionButtons:[HTPressableButton] = []

    override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view.


      //Declaration of Width and Height to avoid calculate this value in each button.
      BUTTON_WIDTH = UIScreen.mainScreen().bounds.width-210;
      BUTTON_HEIGHT = UIScreen.mainScreen().bounds.width-240;


      optionButtons_0 = HTPressableButton(frame: firstFrameOp, buttonStyle: HTPressableButtonStyle.Rect) //firstOption
      optionButtons_1 = HTPressableButton(frame: secondFrame, buttonStyle: HTPressableButtonStyle.Rect) 
      optionButtons_2 = HTPressableButton(frame: thirdFrame, buttonStyle: HTPressableButtonStyle.Rect) 
      optionButtons_3 = HTPressableButton(frame: fourthFrame, buttonStyle: HTPressableButtonStyle.Rect) 

      // lblAnswer.font = UIFont(name: lblAnswer.font.fontName, size: (lblAnswer.font?.pointSize)!)

       optionButtons.append(optionButtons_0, optionButtons_1, optionButtons_2, optionButtons_3)
    }