Swift:从数组中删除特定对象的更好方法? [英] Swift: Better way to remove a specific Object from an array?

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

问题描述

我正在努力提高代码的效率,但我脑子里放了个屁.我编写的这段代码效果很好,并且完全符合我的需要:它检查数组并删除未知索引处的对象.但我觉得有一种更好、更有效的方式来编写它.我去了 Array.remove(at:) 但这需要一个已知的索引.我正在使用大 O 符号,但不知道如何使其更易于处理.有什么想法吗?

I'm trying to be more efficient with my code, but I'm having a brain fart. This code I wrote works great, and does exactly what I need it to do: It checks an array and removes an Object at an unknown Index. But I feel there is a better, more efficient way to write it. I went to Array.remove(at:) but that requires a known index. I'm getting into big O notation and don't know how to make this easier to process. Any ideas?

 // create a new object array
 var sort : [MyCustomObject] = []

//iterate through my object array  

        for i in objectArray{
            if i === objectToRemove{
            }
            else{
                sort.append(i)
            }
        }

     // set old array to sort, which no longer has the unwanted object 
        self.objectArray = sort

推荐答案

使用 firstIndex(where:)(以前在 Swift 4.1 和更早版本中称为 index(where:))以在数组中搜索您的对象使用谓词 { $0 === objectToRemove },然后调用 remove(at:) 在数组上删除它:

Use firstIndex(where:) (previously called index(where:) in Swift 4.1 and earlier) to search the array for your object using the predicate { $0 === objectToRemove }, then call remove(at:) on the array to remove it:

if let idx = objectArray.firstIndex(where: { $0 === objectToRemove }) {
    objectArray.remove(at: idx)
}

这允许您搜索您的对象是否Equatable.

This allows you to search for your object whether it is Equatable or not.

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

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