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

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

问题描述

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

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

它给我3个错误

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'


推荐答案

Swift(3)相当于 NSMutableArray removeObject

The Swift (3) equivalent to NSMutableArray's removeObject is

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

if let index = array.index(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:

如果同一对象出现多次,请使用过滤器。但是,在像数据源数组这样的情况下,索引与特定对象关联索引(更可取,因为它比过滤器

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

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

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