Fatal Error: Array Index out of range in Swift Xcode6

Goh Weai Peng picture Goh Weai Peng · Dec 19, 2014 · Viewed 20k times · Source

I keep getting this error in my func

I'm trying to read the value in array answerRecord. I uses a global var arrayCount, which keep track which index im currently pointing to.

func buttonColourControl(){
    switch answerRecord[arrayCount]{
    case1: xxxxxxx

I did a println in my earlier func and it return a value of int 1 for the var arrayCount Therefore arrayCount is not empty. So it should be able to interpret the array as:

*assuming arrayCount is now 1 answerRecord[arrayCount] should be interpreted as answerRecord[1] Please correct me if im wrong

@IBAction func nextButtonClicked(sender: UIButton) {
    arrayCount = ++arrayCount
    question.text = spouseQuesion[arrayCount]
    controlBackNextButton()
    answer1Label.text = spouseAnswer1[arrayCount]
    answer2Label.text = spouseAnswer2[arrayCount]
    answer3Label.text = spouseAnswer3[arrayCount]
    println(arrayCount)
    buttonColourControl()
}

Answer

matt picture matt · Dec 19, 2014

Let's say you have an array with one object in it:

let arr = ["hello"]

The only valid index into that array is 0. arr[0] is legal. arr[1] is not. The array has 1 element but its index number is 0.

This is true for any array. Every array holds some number of elements. It might be 0 elements, in which case no index is legal. It might be 3 elements, in which case you can refer to the array's elements by index numbers 0, 1, and 2. And so on. That's all. Those are the rules. You cannot use any other index number or you will crash.

So the error message is simply telling you that you are making that mistake. You have an array answerRecord and it has some number of elements - I have no idea how many, and it doesn't matter. Then you are using the expression answerRecord[arrayCount] and the value of arrayCount is outside the bounds I have just explained. That's all you need to know. The error message tells you the bug in your program. Now you can fix it.