In my application i used tableview. I added one object in array when select cell and unselect and remove object when re-select cell. i used that code but give me error. Please help me
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let cell = tableView.cellForRow(at: indexPath as IndexPath) as? ConctactsCell
cell?.imgCheckMark.image = UIImage(named:"check_mark")
arrContacts.append(contacts[indexPath.row] )
NSLog("selected code = %@",arrContacts);
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath as IndexPath) as? ConctactsCell
cell?.imgCheckMark.image = UIImage(named:"")
arrContacts.removeObject(contacts[indexPath.row])
}
extension Array {
func indexOfObject(object : AnyObject) -> NSInteger {
return (self as NSArray).indexOfObject(object)
}
mutating func removeObject(object : AnyObject) {
for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object) {
self.removeAtIndex(index)
}
}
}
It gives me 3 error like that
Declaration is only valid at file scope
C-style for statement has been removed in Swift 3
Value of type '[Any]' has no member 'removeObject'
Another nice and useful solution is to create this kind of extension:
In this way, if you have your array with custom objects:
Extension declaration need to be outside class scope, move it out
for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object)
is for loop in C-style and has been removedChange your code to something like this to remove all similar object if it have looped:
Try this in Swift 3
Instead of
Update
Make sure the object is in scope. You can give scope "internal", which is default.
index(of:<Object>)
to work, class should conform toEquatable