Swift-致命错误:数组索引超出范围 [英] Swift - fatal error: Array index out of range

查看:370
本文介绍了Swift-致命错误:数组索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用每个数字增加0.1的数字填充数组,例如:[0.1,0.2,0.3 ...]

I'm trying to populate an array with numbers with an increase of 0.1 each like: [0.1,0.2,0.3...]

此代码给我错误:fatal error: Array index out of range .我想念什么?我是在说一些错误.

This code is giving me the error: fatal error: Array index out of range . What am I missing? I thing im declaring something wrong.

我将其保存为Double类型的结构.

I will save it into a structure of type 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之间.

UPDATE: Finally made it, but there are this strange numbers between 6 and 10.

在此处输入图片描述

推荐答案

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

You can not add items to a Swift array with the subscript operator, you need to use append.

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

NOTE You can’t use subscript syntax to append a new item to the end of an array."

摘录自:Apple Inc."Swift编程语言(Swift 2预发行版)." iBooks. https://itun.es/us/k5SW7.l

Excerpt From: Apple Inc. "The Swift Programming Language (Swift 2 Prerelease)." iBooks. https://itun.es/us/k5SW7.l

使用append(),例如:

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

这篇关于Swift-致命错误:数组索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆