Find custom index of object in array

I have an array of custom object named Service

, and in didSelectRow

I populate the allocated array of that object:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        let services:[Service] = self.menu[indexPath.section].services
        self.selectedServices.append(services[indexPath.row])
    }
}

      

The problem is I can't figure out how to extract it from the didDeselectRow:

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        cell.accessoryType = .None
        let services = self.menu[indexPath.section].services
        let service = services[indexPath.row]
        //how can I found the index position of service inside selectedServices?

    }

}

      

+3


source to share


1 answer


I suggest you do not store selectedServices

, but rely on UITableView.indexPathsForSelectedRows

.

var selectedServices: [Service] {
    let indexPaths = self.tableView.indexPathsForSelectedRows ?? []
    return indexPaths.map { self.menu[$0.section].services[$0.row] }
}

      

This way you don't have to manually maintain selectedServices

and remove the entire feature tableView(_:didSelectRowAtIndexPath:)

.




If you must maintain separate state, you can find the service using index(where:)

or index(of:)

- see How do I find the index of a list item in Swift? ...

if let i = (self.selectedServices.index { $0 === service }) {
// find the index `i` in the array which has an item identical to `service`.
    self.selectedServices.remove(at: i)
}

      

+4


source







All Articles