Member-only story
Remove elements from an array during enumeration
AKA: .enumerate().reversed() or .reversed().enumerate() confusion, why can’t I just filter and get the result efficiently?
Difficulty: Easy | Normal | Challenging
Prerequisites:
- None
Terminology
Enumeration: A complete, ordered listing of all the items in a collection
The problem
You want to iterate through a list and remove elements that conform to some condition. The examples below might seem quite abstract, but there are many cases where this is important and simple filters may not quite fulfil your needs.
The example here is you have an array of times (in milliseconds) and you want to return the number of elements that are within 1000 milliseconds of the last element. The array is in time order, and has at least one element.
Therefore:
[1,2,3,1000] = [1,2,3,1000]
[1000,1001,1004,2000] = 1
- The easy solution
Filtering has a time complexity of O(n), and gives us a short and easy to understand solution
var last = input.last!
input.filter{ $0 — input.last! <= 1000}