-3

When I run the game, it will usually crash around the 19th wall, proceeding to tell me that "Array index out of range". Im not so fond of swift and have spent an hour so far without success. How to resolve error?

import Foundation
import UIKit

let kMLGroundHeight: CGFloat = 20.0

let kDefaultXToMovePerSecond: CGFloat = 320.0

//CollisionDetection

let heroCategory: UInt32 = 0x1 << 0
let wallCategory: UInt32 = 0x1 << 1

//Levels
let kLevelGenerationTimes: [NSTimeInterval] = [0.8, 0.7, 0.6, 0.4, 0.3]
let kNumberOfPointsPerLevel = 5
7
  • please let me know if i forgot to post something so i can do so. Commented Aug 24, 2015 at 3:35
  • 4
    What's the line where it crashes? It doesn't seem to be any of those Commented Aug 24, 2015 at 3:36
  • All the lines you posted are constants. What does your app actually do? Commented Aug 24, 2015 at 3:36
  • 1
    Swift is fine. You have a logic problem in your code; you are accessing an array as if it had more elements than it actually does. Post the actual code where it crashes if you want help but the Xcode debugger can fix this easily if you set a breakpoint in the code causing the issue. Commented Aug 24, 2015 at 3:44
  • What do you mean? When I run the game, the app crashes and Xcode says " array index out of range". Though how could that be when the elements are equal ? Commented Aug 24, 2015 at 4:03

1 Answer 1

0

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 kLevelGenerationTimes and it has 5 number of elements. Then you are accessing an element which 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.

Reference from HERE.

Sign up to request clarification or add additional context in comments.

Comments

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.