Swift中的索引超出范围错误

时间:2017-10-31 04:48:57

标签: swift breakpoints

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错误。我不完全确定索引的含义或潜在的错误。代码将运行一次然后函数调用自身,并在第二次通过它分解我上面提到的那一行。我检查了所有变量,但没有一个是nill。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

在这里,我举了一个简短的例子,让您了解问题的实际位置。

ScreenShot 1:

enter image description here

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

在第一次调用时,要么将值递减为numberAtCounter-=1,其值从0到-1。因此在第二次调用时,函数在行中被调用:

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

确保它没有比peopleInMatch数组更多的负值或值。

因此,如果它变为负数或超过计数,结果将得到如下结果:

enter image description here