Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

xcode6.1 - Fatal Error: Array Index out of range in Swift Xcode6

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()
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...