Why does filters in Swift iterate the collection twice?

swift

Solution

Most probably `filter` is implemented to first count the number of elements it needs to store and then, after using that number to size the allocation of storage for a new array, looping again to copy the ones he needs to keep.

The fact that it loops only once if you always return `false` means that it optimizes away the second cycle iff the result is empty.

You may want to radar this as a bug but it probably is "working as designed": arrays are not lists, after all.

Problem

The following code in Swift's playground or Console App: ``` let letters = ["A", "B", "C"] letters.filter({ (x : String) -> Bool in println("PRINT: \(x)") return true }) ``` Prints out: ``` PRINT: A PRINT: B PRINT: C PRINT: A PRINT: B PRINT: C ``` Why does it iterate over the collection twice?

Original source