在 Swift 3 中从数组中删除对象 [英] Removing object from array in Swift 3

查看:19
本文介绍了在 Swift 3 中从数组中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我在选择单元格时在数组中添加了一个对象,在重新选择单元格时取消选择并删除对象.我使用了那个代码,但给了我错误.

In my application 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.

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)
        }
    }
}

class MyViewController: UITableViewController {
    var arrContacts: [Any] = []
    var contacts: [Any] = []

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        arrContacts.removeObject(contacts[indexPath.row])
    }
}

它给了我 2 个这样的错误:

It gives me 2 error like that:

C-style for statement has been removed in Swift 3
Value of type '[Any]' has no member 'removeObject'

推荐答案

Swift 等价于 NSMutableArrayremoveObject 是:

The Swift equivalent to NSMutableArray's removeObject is:

var array = ["alpha", "beta", "gamma"]

if let index = array.firstIndex(of: "beta") {
    array.remove(at: index)
}

如果对象是唯一的.根本不需要转换为 NSArray 并使用 indexOfObject:

if the objects are unique. There is no need at all to cast to NSArray and use indexOfObject:

API index(of: 也可以工作,但这会导致不必要的隐式桥转换到 NSArray.

The API index(of: also works but this causes an unnecessary implicit bridge cast to NSArray.

如果同一对象多次出现,请使用 filter.但是,在索引与特定对象关联的数据源数组等情况下,firstIndex(of 是可取的,因为它比 filter 更快.​​

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 object firstIndex(of is preferable because it's faster than filter.

更新:

在 Swift 4.2+ 中,您可以使用 beta="noreferrer">removeAll(where:):

In Swift 4.2+ you can remove one or multiple occurrences of beta with removeAll(where:):

array.removeAll{$0 == "beta"}

这篇关于在 Swift 3 中从数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆