How can I check if an indexPath is valid, thus avoiding an "attempt to scroll to invalid index path" error?

webmagnets picture webmagnets · Apr 8, 2015 · Viewed 28.4k times · Source

How can I check to see whether an indexPath is valid or not?

I want to scroll to an indexPath, but I sometimes get an error if my UICollectionView subviews aren't finished loading.

Answer

muffe picture muffe · Apr 8, 2015

You could check

- numberOfSections
- numberOfItemsInSection: 

of your UICollection​View​Data​Source 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
    }

}