Swift - 致命错误:数组索引超出范围

时间:2015-08-29 15:54:27

标签: ios swift

我正在尝试用数字填充数组,每个数字增加0.1,如:[0.1,0.2,0.3 ...]

此代码给出了错误:fatal error: Array index out of range 。我错过了什么?我事实上我宣布了一些错误。

我将它保存为Double类型的结构。

我的代码

import UIKit

class PrecoDomicilioViewController: UIViewController,UIPickerViewDelegate, UIPickerViewDataSource{

@IBOutlet var euros: UIPickerView!

var pickerData:[Double] = []


override func viewDidLoad() {
    super.viewDidLoad()

    euros.delegate = self
    euros.dataSource = self




    for var i = 0; i <= 200; i++
    {
        pickerData[i] += 0.1
    }

}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    return pickerData.count
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

    return "\(pickerData[row])"
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    restaurante.portes = pickerData[row]
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


}
}

更新: 终于做到了,但是在6到10之间有这个奇怪的数字。

enter image description here enter image description here

1 个答案:

答案 0 :(得分:2)

您不能使用下标运算符将项添加到Swift数组中,您需要使用append。

  

请注意   您不能使用下标语法将新项目附加到数组的末尾。“

摘录自:Apple Inc.“The Swift Programming Language(Swift 2 Prerelease)。”iBooks。 https://itun.es/us/k5SW7.l

使用append(),示例:

shoppingList.append("Flour")
pickerData.append(0.1)