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

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

问题描述

我正在尝试提高代码的效率,但是我脑子屁.我编写的这段代码非常有用,并且完全满足我的需要:它检查一个数组,并从一个未知的索引处删除一个Object.但是我觉得有一种更好,更有效的编写方法.我去了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 }在数组中搜索对象,然后调用

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天全站免登陆