2

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

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

I will save it into a structure of type Double.

My Code

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()
}


}
}

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

enter image description here enter image description here

3
  • What line does the error occur on? Commented Aug 29, 2015 at 15:56
  • pickerData[i] += 0.1 Commented Aug 29, 2015 at 15:57
  • 1
    You really need a separate question. Hint: floating point numbers can not represent most decimal numbers (non whole numbers) exactly, that is what you ar seeing here. It is a problem when changing bases, here from base 10 to base 2 which Double uses. For exact decimal numbers such as for money and calculators use NSDecimalNumber. Commented Aug 29, 2015 at 16:16

1 Answer 1

2

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.”

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

Use append(), examples:

shoppingList.append("Flour")
pickerData.append(0.1)
Sign up to request clarification or add additional context in comments.

3 Comments

How do I populate with append?
Solved my question. In other languages we simply use +=. Thank you.
In Swift += is used for append an array, ex: shoppingList += ["Baking Powder", "Tomatoes"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.