Collin Stover Collin Stover - 1 year ago 123
iOS Question

Swift: Getting EXC_BAD_INSTRUCTION when trying to append random array elements

I am getting the error, "Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)" when trying to append random array elements into a new array.

The debug log says "fatal error: Index out of range"

//If there are more than 6 players prioritizing the event, make a random choice. garudaLocations is an array containing the players who prioritized the event "Garuda".

if garudaLocations.count > 6 {

var finalGarudaPlayers : [Int] = []
let getRandom = randomSequenceGenerator(1, max: garudaLocations.count) //Tell RNG how many numbers it has to pick from.
var randomGarudaPrioritiesIndex = Int()
for _ in 1...6 {
randomGarudaPrioritiesIndex = getRandom() //Generate a random number.
finalGarudaPlayers.append(garudaLocations[randomGarudaPrioritiesIndex]) //ERROR: Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)
debugPrint(finalGarudaPlayers) //Print array with the final priority Garuda members.

randomSequenceGenerator is a function I got from here, which does work to generate the random numbers.

func randomSequenceGenerator(min: Int, max: Int) -> () -> Int {
var numbers: [Int] = []
return {
if numbers.count == 0 {
numbers = Array(min ... max)

let index = Int(arc4random_uniform(UInt32(numbers.count)))
return numbers.removeAtIndex(index)

To get a better understanding, I am trying to write a piece of a "team making" program where players are automatically sorted into events, but they can choose which events they would like to prioritize.

I can only have 6 people per event, however, so the goal is to take the existing garudaLocations array, choose a random 6 index locations, and get rid of the rest of the players.

I get the error only after I submit more than 6 players to the same event.

Any help is very much appreciated!

Answer Source

You can never speak of a non-existent index. If you do, you will crash just as you are crashing now.

So, you are saying:


Now, I do not know what garudaLocations is. But I can tell you for certain that if randomGarudaPrioritiesIndex is not an existing index within garudaLocations, you will absolutely crash.

Thus, you can easily debug this by logging (print) randomGarudaPrioritiesIndex.

Bear in mind that the largest existing index is not garudaLocations[garudaLocations.count]. It is garudaLocations[garudaLocations.count-1]. So compare randomGarudaPrioritiesIndex to garudaLocations.count-1. If it is greater, you crash when you use it as an index on garudaLocations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download