Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Swift’s filter method stable?

Tags:

arrays

swift

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]

?

like image 711
user3770280 Avatar asked Apr 03 '15 22:04

user3770280


People also ask

How does filter work in Swift?

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.

Does filter modify the original Array Swift?

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.


1 Answers

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 of source, 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.

like image 56
matt Avatar answered Sep 23 '22 12:09

matt