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

Solution 1:

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
    }

}

Solution 2:

A more concise solution?

func indexPathIsValid(indexPath: NSIndexPath) -> Bool {
    if indexPath.section >= numberOfSectionsInCollectionView(collectionView) {
        return false
    }
    if indexPath.row >= collectionView.numberOfItemsInSection(indexPath.section) {
        return false
    }
    return true
}

or more compact, but less readable...

func indexPathIsValid(indexPath: NSIndexPath) -> Bool {
    return indexPath.section < numberOfSectionsInCollectionView(collectionView) && indexPath.row < collectionView.numberOfItemsInSection(indexPath.section)
}