Removing object from array in swift 3

2019-02-07 15:51发布

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'

9条回答
看我几分像从前
2楼-- · 2019-02-07 16:40

Another nice and useful solution is to create this kind of extension:

extension Array where Element: Equatable {

    @discardableResult mutating func remove(object: Element) -> Bool {
        if let index = index(of: object) {
            self.remove(at: index)
            return true
        }
        return false
    }

    @discardableResult mutating func remove(where predicate: (Array.Iterator.Element) -> Bool) -> Bool {
        if let index = self.index(where: { (element) -> Bool in
            return predicate(element)
        }) {
            self.remove(at: index)
            return true
        }
        return false
    }

}

In this way, if you have your array with custom objects:

let obj1 = MyObject(id: 1)
let obj2 = MyObject(id: 2)
var array: [MyObject] = [obj1, obj2]

array.remove(where: { (obj) -> Bool in
    return obj.id == 1
})
// OR
array.remove(object: obj2) 
查看更多
放我归山
3楼-- · 2019-02-07 16:40
  1. Extension declaration need to be outside class scope, move it out

  2. for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object) is for loop in C-style and has been removed

  3. Change your code to something like this to remove all similar object if it have looped:

    let indexes = arrContacts.enumerated().filter { $0.element == contacts[indexPath.row] }.map{ $0.offset }
    for index in indexes.reversed() {
       arrContacts.remove(at: index)
    }
    
查看更多
冷血范
4楼-- · 2019-02-07 16:42

Try this in Swift 3

array.remove(at: Index)

Instead of

array.removeAtIndex(index)

Update

"Declaration is only valid at file scope".

Make sure the object is in scope. You can give scope "internal", which is default.

index(of:<Object>) to work, class should conform to Equatable

查看更多
登录 后发表回答