When I filter an array in Swift, can I expect the results to be in the same order as the original? For example, can I count on:
[3, 1, 4, 1, 5, 9, 2, 7].filter{$0 > 4}
always returning:
[5, 9, 7]
?
The filter function loops over every item in a collection, and returns a collection containing only items that satisfy an include condition. It's like applying an if-statement to a collection, and only keeping the values that pass the condition.
When you apply a filter on an Array, the original Array is not modified. Instead, filter(isIncluded:) creates a new Array with only the elements you want.
Yes, you can count on it. The filter
instance method of Array calls the global filter
method, whose comment in the Swift header file explicitly says:
Return an
Array
containing the elements ofsource
, in order, that satisfy the predicate
(my italics).
Moreover, the whole point of these methods on Array such as map
and filter
(and, for that matter, reduce
) is that an array is ordered and they cycle through the array in that order. An Array is a sequence (a SequenceType): it has a generator with a next()
method that is called repeatedly in order to cycle through the array in order, and this next()
method is how such methods do cycle through the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With