由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:“尝试滚动到无效的索引路径

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path

我的应用程序崩溃了,我的 UICollectionView 中有 300 个单元格,而我 select 单元格号。 300 向我展示这次崩溃:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: {length = 2, path = 0 - 300}'

代码:

var EnabledID = Int()
EnabledID = UserDefaults.standard.integer(forKey: "EnabledID")

if EnabledID == 0 {
    EnabledID = 1
    UserDefaults.standard.set(1, forKey: "EnabledID")

} else {
    let index = NSIndexPath(item: EnabledID, section: 0)
    self.myCollectionView.scrollToItem(at: index as IndexPath, at: .centeredHorizontally, animated: true)
}

请帮我解决这个问题:)

检查数组计数

if EnabledID < arr.count
{
    let index = NSIndexPath(item: EnabledID, section: 0)
    self.myCollectionView.scrollToItem(at: index as IndexPath, at: .centeredHorizontally, animated: true)
}