Swift 中的索引超出范围错误

Index Out of Range Error in Swift

var numberOfPeople = 1 //get from host
var numberAtCounter = 0
func showNames() {

    if peopleInMatch[numberAtCounter] == yourPeerID { //change to peopleinmatcheveryone

        if numberOfPeople == 0 {
            print("hoho")
            personName.isHidden = true
            connect.isHidden = false
            connect.setTitle("PRESS READY", for: UIControlState.normal)
            //change label to ready
        } else {
            numberAtCounter += 1
            numberOfPeople -= 1 // buggy?
            print("\(numberAtCounter)")
            showNames()
        }


    } else {
    personName.text = "TAKE PHOTO OF \(peopleInMatch[numberAtCounter])'s COLOR"
    numberAtCounter += 1
        if numberOfPeople <= 0 {
            personName.isHidden = true
            connect.isHidden = false
            connect.setTitle("PRESS READY", for: UIControlState.normal)
            //change label to ready
        }
    numberOfPeople -= 1 //buggy maybe fixed

    }
}

我在 if peopleInMatch[numberAtCounter] == yourPeerID 行中收到线程 1: EXC_BREAKPOINT 错误。我不完全确定 out of index 意味着什么或可能有什么错误。代码将是 运行 一次,然后函数调用自身,第二次通过它在我上面提到的行上分解。我检查了所有变量,其中 none 为空。有什么想法吗?

这里我做了一个简短的例子,让你明白你的问题到底出在哪里。

屏幕截图 1:

当第一次调用函数打印 numberAtCounter 的值时,一切正常。

在第一次调用中,您将值递减为 numberAtCounter-=1,它的值从 0 到 -1。因此,在第二次调用中,当函数被在线调用时:

if peopleInMatch[numberAtCounter] == yourPeerID // here you need to check value of `numberAtCounter` 

确保它没有得到负值或大于您的 peopleInMatch 数组的值。

因此如果它变为负数或大于计数,您将得到如下结果: