2016-09-23 42 views
0

我正在错误,“线程1:EXC_BAD_INSTRUCTION(代码= EXC_1386_INVOP,子码=为0x0)”试图追加随机阵列元件到一个新的数组时。夫特:获取EXC_BAD_INSTRUCTION当试图追加随机数组元素

调试日志说:“致命的错误:索引超出范围”

//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,它不工作,产生的随机数。

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) 
    } 
} 

为了得到更好的理解,我试图写一块“团队建设”计划,玩家会被自动分类到事件,但他们可以选择他们希望优先考虑哪些事件。

我只能有6人每个事件,然而,目标是利用现有garudaLocations阵列,随机选择一个6个索引位置,并摆脱其他玩家的。

只有当我提交超过6名选手参加同一个比赛时,我才会收到错误。

任何帮助非常感谢!

回答

1

你可以从来没有说一个不存在的指数。如果你这样做,你会崩溃,就像你现在崩溃一样。

所以,你说:

garudaLocations[randomGarudaPrioritiesIndex] 

现在,我不知道是什么garudaLocations是。但我可以肯定地告诉你,如果randomGarudaPrioritiesIndex不是garudaLocations中的现有索引,那么你绝对会崩溃。

因此,您可以通过日志记录(printrandomGarudaPrioritiesIndex轻松进行调试。

请记住,现有的最大指数不是garudaLocations[garudaLocations.count]。它是garudaLocations[garudaLocations.count-1]。所以比较randomGarudaPrioritiesIndexgarudaLocations.count-1。如果它更大,当您将它用作garudaLocations上的索引时会崩溃。

+0

garudaLocations是包含选择事件作为优先级的玩家的阵列。 randomGarudaPrioritiesIndex是一个保存随机数的变量(由randomSequenceGenerator函数生成)。例如,您通常会使用(array [X])列出数组中的元素X.我认为我可以在0的位置使用随机数发生器,这样我就可以找到一个* random *数组元素。情况并非如此吗? –

+0

当我debugPrint(randomGarudaPrioritiesIndex)我得到6个随机整数,如预期的(不在数组中)。 –

+0

所有这一切都很棒。但似乎无关紧要;问题是这些随机整数是否合法用于表达'garudaLocations [randomGarudaPrioritiesIndex]'中。显然,有时并非如此。 – matt