【问题标题】:Swift: How can I prevent a Index out of range in this instanceSwift:在这种情况下如何防止索引超出范围
【发布时间】:2019-12-26 17:24:59
【问题描述】:

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

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

谢谢

【问题讨论】:

  • allPlayers 应该有 3 * 7 = 21 项。如果它没有 21 项目,那么你的整个逻辑就是错误的。你看错地方了。
  • 为什么不遍历玩家数组而不是两个嵌套循环呢?这将彻底解决索引问题。

标签: swift swift4.2


【解决方案1】:

let isIndexValid = array.indices.contains(index)

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

这会起作用。

【讨论】:

  • 在循环顶部添加 IF 语句对我不起作用,但这非常有效。谢谢大家的建议
【解决方案2】:

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

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

但是,这只会防止“索引超出范围”,而不会改善实际逻辑。贴出完整的代码,让完整的逻辑通俗易懂。

【讨论】:

  • 正确,但我会在循环顶部创建if 条件以防止创建按钮、添加子视图等
  • 是的,这样更好。
猜你喜欢
  • 2021-01-28
  • 2021-12-03
  • 1970-01-01
  • 2017-06-20
  • 2023-04-03
  • 2018-05-07
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多