问题描述
我的数组中有大约2000个元素,当对其进行过滤时,只要过滤的数组中有5个元素,我就想结束过滤.
I have about 2000 elements in my array, and when it is filtered, I would like to end the filtering as soon as I have 5 elements in my filtered array.
当前是:
providerArray.filter({($0.lowercased().range(of:((row.value as? String)?.lowercased())!) != nil)})
最多可以返回2000个结果,这浪费了处理时间和时间.
which can return up to 2000 results which is a waste of processing, and time.
更清楚地说,我需要一个解决方案,它等同于限制过滤器结果,就像我可以使用coreData提取[request setFetchLimit:5];
To be more clear, I need a solution that is equivalent to limiting the filter results like I can with coreData fetches [request setFetchLimit:5];
推荐答案
就执行时间而言,最快的解决方案似乎是显式循环,添加匹配的元素直到达到限制:
The fastest solution in terms of execution time seems to be anexplicit loop which adds matching elements until the limit is reached:
extension Sequence {
public func filter(where isIncluded: (Iterator.Element) -> Bool, limit: Int) -> [Iterator.Element] {
var result : [Iterator.Element] = []
result.reserveCapacity(limit)
var count = 0
var it = makeIterator()
// While limit not reached and there are more elements ...
while count < limit, let element = it.next() {
if isIncluded(element) {
result.append(element)
count += 1
}
}
return result
}
}
示例用法:
let numbers = Array(0 ..< 2000)
let result = numbers.filter(where: { $0 % 3 == 0 }, limit: 5)
print(result) // [0, 3, 6, 9, 12]
这篇关于将Swift数组过滤器的结果限制为X以提高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!