Search code examples
iosarraysswiftuicollectionviewindexpath

Swift- Converting Index path array to Int array


I'm trying to produce an array of selected values from a UICollectionView in swift 4. Im using the self.collectionView.indexPathsForSelectedItems method which returns the selected items as an Array of type index path. For example if elements 0 and 2 were selected, it returns [[0, 0], [0, 2]] I'd like to know how to process this into an array of type Int to store it as [0,2].

I've been trying for hours any any help would be GREATLY appreciated, thank you.


Solution

  • You can use map function for this:

    guard let indexPaths: [IndexPath] = collectionView.indexPathsForSelectedItems else { return }
    let indexes = indexPaths.map({ $0.item })
    

    Or Force Unwrap:

    let indexes = collectionView.indexPathsForSelectedItems!.map{ $0.item }
    

    Another option as suggested on comment section

    let indexes = (collectionView.indexPathsForSelectedItems ?? []).map{ $0.row }