gpt4 book ai didi

ios - Swift:尝试附加随机数组元素时获取 EXC_BAD_INSTRUCTION

转载 作者:行者123 更新时间:2023-11-28 16:10:18 24 4
gpt4 key购买 nike

我在尝试将随机数组元素附加到新数组时收到错误消息,“线程 1:EXC_BAD_INSTRUCTION(代码=EXC_1386_INVOP,子代码=0x0)”

调试日志显示“ fatal error :索引超出范围”

//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.

随机序列生成器 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)
}
}

为了更好地理解,我正在尝试编写一个“团队 build ”程序,其中玩家会自动分类到事件中,但他们可以选择他们想要优先处理的事件。

但是,我每个事件只能有 6 个人,所以目标是采用现有的 garudaLocations 数组,随机选择 6 个索引位置,然后去掉其余的玩家。

只有在我将超过 6 名玩家提交到同一事件后,我才会收到错误消息。

非常感谢任何帮助!

最佳答案

永远不能说索引不存在。如果这样做,您将像现在一样崩溃。

所以,你是说:

garudaLocations[randomGarudaPrioritiesIndex]

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

因此,您可以通过记录 (print) randomGarudaPrioritiesIndex 轻松调试它。

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

关于ios - Swift:尝试附加随机数组元素时获取 EXC_BAD_INSTRUCTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39650705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com