Is the Swifts filter method stable?

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 returns:

 [5, 9, 7] 

?

+5
source share
2 answers

Yes, you can count on it. The filter instance instance method calls the global filter method, whose comment in the Swift header file explicitly says:

Returns a Array containing source elements, in order to satisfy the predicate

(italics mine).

In addition, the whole point of these methods in the array, such as map and filter (and, for that matter, reduce ), is that the array is ordered and they cycle through the array in that order. An array is a sequence (type SequenceType): it has a generator with the next() method that is called multiple times to cycle through the array in order, and this next() method is how such methods loop through the array.

+8
source

Although this is not explicitly stated, it seems to be happening as per the examples in the documentation

 let array = [0, 1, 2, 3, 4, 5, 6, 7] let filteredArray = array.filter { $0 % 2 == 0 } // filteredArray is [0, 2, 4, 6] 

Massive manipulation methods tend to maintain order in all directions when it makes sense, and he is here. I would be very surprised if he did not return in the same order. But again, since this is not explicitly mentioned, it might be a good idea to write a check in the form of an assertion in case they change it line by line.

+3
source

All Articles