ios - Find custom Object index in array -
i have array of custom object called service
, in didselectrow
populate selected array of 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 can't figure out how retrieve 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 found index position of service inside selectedservices? } }
i suggest don't store selectedservices
, rely on uitableview.indexpathsforselectedrows
.
var selectedservices: [service] { let indexpaths = self.tableview.indexpathsforselectedrows ?? [] return indexpaths.map { self.menu[$0.section].services[$0.row] } }
this way, don't need manually maintain selectedservices
, remove entire tableview(_:didselectrowatindexpath:)
function.
if must maintain separate state, find service using index(where:)
or index(of:)
— see how find index of list item in swift?.
if let = (self.selectedservices.index { $0 === service }) { // find index `i` in array has item identical `service`. self.selectedservices.remove(at: i) }
Comments
Post a Comment