3

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?

    }

}
3
  • selectedServices[indexPath.row] how about Commented Apr 14, 2017 at 16:42
  • Have you tried self.selectedServices[indexPath.row] ? Commented Apr 14, 2017 at 16:43
  • No please read the code Commented Apr 14, 2017 at 16:45

1 Answer 1

5

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that's an answer ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.