You could check
- numberOfSections
- numberOfItemsInSection:
of your UICollectionViewDataSource
to see if your indexPath is a valid one.
E.g.
extension UICollectionView {
func isValid(indexPath: IndexPath) -> Bool {
guard indexPath.section < numberOfSections,
indexPath.row < numberOfItems(inSection: indexPath.section)
else { return false }
return true
}
}