Federic
Federic

Reputation: 91

Find custom Object index in array

I have an array of custom object called Service and in didSelectRow I populate my selected 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 that I can't figure out how to retrieve it from 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?

    }

}

Upvotes: 3

Views: 900

Answers (1)

kennytm
kennytm

Reputation: 523234

I suggest you don't store the 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 need to manually maintain selectedServices and could remove the entire tableView(_:didSelectRowAtIndexPath:) function.


If you must maintain a separate state, you could find the service using index(where:) or index(of:) — see How to find index of 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)
}

Upvotes: 5

Related Questions