RDowns RDowns - 9 days ago 7
Swift Question

How do I access just the second part of these arrays in Swift 3?

I use the following function so I can select 2 rows in a table:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

self.selectedCellTitle = self.communityPlayers[indexPath.row]
cellId = indexPath.row
//print (self.communityPlayerIds[indexPath.row])

if let cell = tableView.cellForRow(at: indexPath) {
if cell.isSelected {
cell.accessoryType = .checkmark
}
}

if let sr = tableView.indexPathsForSelectedRows {
print("didSelectRowAtIndexPath selected rows:\(sr)")
if sr.count == 2{
print ("one ", sr[0])
print ("two ", sr[1])
}
}


}


the
print("didSelectRowAtIndexPath selected rows:\(sr)")
line outputs something like this:


didDeselectRowAtIndexPath selected rows:[[0, 2], [0, 3]]


I want to access the second int only in each array (discarding the 0's). I have tried using
print ("one ", sr[0])
to attempt this but this outputs the following:


one [0, 2]


In the example above I only want to access the
2
so I can store that in a separate variable.

How can I access the second part only of these arrays? (the 2, and 3)

Answer

If you want an array containing just the second numbers, you can use a map, like this:

sr.map { $0[1] }

Or, since they are index paths, this is neater:

sr.map { $0.row }