首页 > 解决方案 > iOS Swift Is it worth trying to remove objects from a Swift array when filtering?

问题描述

I have a table view with 30 rows. There are 10000 data points that are ordered chronologically. Each table view cell pulls out about 300 data points based on a filter clause. I have not seen the equivalent of "removeObjectsInArray" for Swift arrays removeObjects(in:)

I'm not sure if Swift's treatment of arrays would re-allocate the entire array, causing a bigger performance hit then gained by reducing the array size.

标签: iosarraysswiftnsmutablearray

解决方案


最好不要做一些强制转换来做这些事情,这可以通过纯粹的快速方法来完成。

这是一个例子:

    var mainArraySwift: [String] = []
    mainArraySwift.append("a")
    mainArraySwift.append("b")
    mainArraySwift.append("c")
    mainArraySwift.append("d")
    mainArraySwift.append("e")
    print(mainArraySwift)

    var arrayToBeRemoved: [String] = []
    arrayToBeRemoved.append("a")
    arrayToBeRemoved.append("b")
    arrayToBeRemoved.append("c")
    print(arrayToBeRemoved)

    mainArraySwift.removeAll { (value) -> Bool in
        return arrayToBeRemoved.contains(value)
    }
    print(mainArraySwift)

输出是:

["a", "b", "c", "d", "e"]
["a", "b", "c"]
["d", "e"]

与 NSMutableArray 的方法不完全匹配,但这是您感兴趣的事情。


推荐阅读