Swift:如何在这种情况下防止索引超出范围

问题描述 投票:1回答:2

我有一个应用程序,其中有一个存储在CoreData中的播放器列表(最多21个)。加载ViewController时,它将在主屏幕上的按钮上显示玩家名称。

但是,我已经赋予用户删除播放器的能力,因为21设置太多了。因此他们删除了,这将按预期从CoreData中删除数据。

然后,他们刷新ViewController,我只想显示仍在CoreData中的播放器数量的按钮。

所以我用了这个代码:-

func reset()
{
    let ksPickButtons = view.subviews.filter{$0 is KSPickButton}
    ksPickButtons.forEach{$0.removeFromSuperview()}

    //sort the player list
    allPlayers.sort()
    playerNo = 0

    //run 2 loops to display the buttons (21 of them)
    for j in 0...2 {
    for i in 0...6 {

            //use the CLASS KSPIckButton to format the buttons
            let buttonOne:UIButton = KSPickButton(frame: CGRect(x: (j + 1) * 35 + (j * 80), y: (i + 5) * 35 + buttonSet, width: 110, height: 30))

            //Add the button to the storyboard
            self.view.addSubview(buttonOne)
            buttonOne.addTarget(self,
                                action: #selector(playerButtons),
                                for: .touchUpInside)
            //assign the tag to the button
            buttonOne.tag = playerNo
            //Give the buttons the players names
            buttonOne.setTitle(allPlayers[playerNo], for: .normal)

        playerNo += 1
    }
    }

    initStart()

}

但是这行

buttonOne.setTitle(allPlayers[playerNo], for: .normal)

给我一个致命的错误:“索引超出范围”,因为不再有21个项目,而我的循环会将playerNo增加到21。

我尝试了“ IF”语句,但是在编译时会忽略它们,并且“索引超出范围”仍然会停止执行代码。

如何识别/停止/跳过错误,仅显示玩家数量的按钮数量?

谢谢

swift swift4.2
2个回答
0
投票

设置标题之前使用if语句。

if allPlayers.count < playerNo {
  buttonOne.setTitle(allPlayers[playerNo], for: .normal)
}

但是,这只会防止“索引超出范围”,而不会改善实际逻辑。发布整个代码,以便可以理解完整的逻辑。


0
投票

let isIndexValid = array.indices.contains(index)

 if isIndexValid == true
 {
  buttonOne.setTitle(allPlayers[playerNo], for: .normal)
 } 
  else
 {
  //do nothing
 }

这将起作用。

© www.soinside.com 2019 - 2024. All rights reserved.