Swift 斯威夫特:在这种情况下,如何防止索引超出范围

Swift 斯威夫特:在这种情况下,如何防止索引超出范围,swift,swift4.2,Swift,Swift4.2,我有一个应用程序,在CoreData中存储了玩家列表(最多21名)。当ViewController加载时,它会在主屏幕的按钮上显示玩家姓名 然而,我已经给了用户删除玩家的能力,因为21个对于他们的设置来说可能太多了。因此,他们删除,这将按预期从CoreData中删除数据 然后他们刷新ViewController,我只想显示CoreData中玩家数量的按钮 所以我用了这个代码:- func reset() { let ksPickButtons = view.subviews.filter

我有一个应用程序,在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”语句,但在编译时忽略了它们,“索引超出范围”仍然会停止代码的执行

如何识别/停止/跳过错误,并仅显示播放器数量的按钮数


谢谢

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

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

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

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

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

let isIndexValid = array.indices.contains(index)

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

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


let isIndexValid = array.indices.contains(index)

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

这会奏效的


这将起作用。

所有玩家
都应该拥有
3*7=21项。如果它没有
21
项,那么您的整个逻辑都是错误的。你找错地方了。为什么不遍历玩家数组而不是两个嵌套循环呢?这将最终解决索引问题。
所有玩家都应该有
3*7=21
项。如果它没有
21
项,那么您的整个逻辑都是错误的。你找错地方了。为什么不遍历玩家数组而不是两个嵌套循环呢?这将最终解决索引问题。正确,但我会在循环顶部创建
if
条件,以防止创建按钮,添加子视图等,这是更好的。正确,但我会在循环顶部创建
if
条件,以防创建按钮,添加子视图等,即,这样更好。在循环的顶部添加一个IF语句对我来说不起作用,但这非常有效。谢谢大家的建议在循环的顶部添加一个IF语句对我来说不起作用,但这非常有效。谢谢大家的建议