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'
For Swift 3, you can use index(where:) and include a closure that does the comparison of an object in the array ($0) with whatever you are looking for.
In Swift 3, Use this
Extention
:example:
The Swift (3) equivalent to
NSMutableArray
'sremoveObject
isif the objects are unique. There is no need at all to cast to
NSArray
and useindexOfObject:
If there are multiple occurrences of the same object use
filter
. However in cases like data source arrays where an index is associated with a particular objectindex(of
is preferable because it's faster thanfilter
.The correct and working one-line solution for deleting a unique object (named "objectToRemove") from an array of these objects (named "array") in Swift 3 is:
Swift 4