Lazy filtering order is now reversed
Lazy filtering order is now reversed êŽë š
Available from Swift 5.2
Thereâs a small change in Swift 5.2 that could potentially cause your functionality to break: if you use a lazy sequence such as an array, and apply multiple filters to it, those filters are now run in the reverse order.
For example, this code below has one filter that selects names that start with S, then a second filter that prints out the name then returns true:
let people = ["Arya", "Cersei", "Samwell", "Stannis"]
.lazy
.filter { $0.hasPrefix("S") }
.filter { print($0); return true }
_ = people.count
In Swift 5.2 and later that will print âSamwellâ and âStannisâ, because after the first filter runs those are the only names that remain to go into the second filter. But before Swift 5.2 it would have returned all four names, because the second filter would have been run before the first one. This was confusing, because if you removed the lazy
then the code would always return just Samwell and Stannis, regardless of Swift version.
This is particularly problematic because the behavior of this depends on where the code is being run: if you run Swift 5.2 code on iOS 13.3 or earlier, or macOS 10.15.3 or earlier, then youâll get the old backward behavior, but the same code running on newer operating systems will give the new, correct behavior.