Skip to main content

Lazy filtering order is now reversed

About 2 minSwiftArticle(s)bloghackingwithswift.comswiftswift-5.2

Lazy filtering order is now reversed ꎀ렚

HACKING WITH SWIFT

What's new in Swift?

Lazy filtering order is now reversed | Changes in Swift 5.2

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.

Other Changes in Swift 5.2
Key path expressions as functions | Changes in Swift 5.2

Key path expressions as functions
Callable values of user-defined nominal types | Changes in Swift 5.2

Callable values of user-defined nominal types
Subscripts can now declare default arguments | Changes in Swift 5.2

Subscripts can now declare default arguments
New and improved diagnostics | Changes in Swift 5.2

New and improved diagnostics

Download Swift 5.2 playground