Lazy sequence with filter

Hi, I was experimenting with the lazy sequence.
But the code below doesn't work as expected.

Code

let array = [0, 1]
let lazySequence = array
    .lazy
    .map { value -> Int in
        print("map1", value)
        return value
    }
    .filter { value -> Bool in
        print("filter", value)
        return value % 2 == 0
    }
    .map { value -> Int in
        print("map2", value)
        return value
    }
print(lazySequence[0])

My expect

map1 0
filter 0
map2 0
0

Result

map1 0
map2 0
0

Question

What is the point of ignoring print("filter", value)?

Swift version

swift-driver version: 1.45.2 Apple Swift version 5.6.1 (swiftlang-5.6.0.323.66 clang-1316.0.20.12)
Target: arm64-apple-macosx12.0
2 Likes

standard library is assuming that the index you're passing in is a valid index, and not a random value someone pulled out of thin air

  • If the index is valid, then the filtering was already performed, no need to duplicate the work
  • If the index is invalid, then it's your fault and your program will crash, or silently return a wrong value.

If you acquire the index the blessed way, filter will be printed

let indexOfTheFirstElement = lazySequence.startIndex
print(lazySequence[indexOfTheFirstElement])

will print

map1 0
filter 0
map1 0
map2 0
0