user8116739
user8116739

Reputation:

This error keeps appearing in my code and I can't figure out how to fix it

I'm making an ios game app in Xcode 8 using swift 3 and I keep getting an error that says "Thread 1: EXC_BAD_INSTRUCTION (codeEXC_1386_INVOP, subcode=0x0)" and a console message that says fatal error: "Index out of range (lldb)". Does anyone know how to fix this?

Here's the section of code with the error. I get it on the line that says 'let nodeB = cableSegments[i]'

for i in 1..<length {
        let nodeA = cableSegments[i - 1]
        let nodeB = cableSegments[i]
        let joint = SKPhysicsJointPin.joint(withBodyA: nodeA.physicsBody!, bodyB: nodeB.physicsBody!,
                                            anchor: CGPoint(x: nodeA.frame.midX, y: nodeA.frame.minY))

        scene.physicsWorld.add(joint)
    }

Upvotes: 1

Views: 44

Answers (1)

Weder Ribas
Weder Ribas

Reputation: 359

The "out of range" error is common in many programming languages. It indicates to you that the loop is trying to access a position in the array that is out of the array range.

Per your code above it's not possible to figure out where are you obtaining the length value, but it should be the array length.

May the code below could work:

var counter = 0

for i in 0..<cableSegments.count {

    counter += 1

    if counter == cableSegments.count {
        break
    }

    let nodeA = cableSegments[i]
    let nodeB = cableSegments[i + 1]
    let joint = SKPhysicsJointPin.joint(withBodyA: nodeA.physicsBody!, bodyB: nodeB.physicsBody!,
                                        anchor: CGPoint(x: nodeA.frame.midX, y: nodeA.frame.minY))

    scene.physicsWorld.add(joint)
}

Upvotes: 2

Related Questions