# Lazy sequence with filter

**URL:** <https://forums.swift.org/t/lazy-sequence-with-filter/59399>\
**Category:** Using Swift\
**Tags:** lazy\
**Created:** [August 2, 2022, 1:04pm UTC](https://forums.swift.org/t/lazy-sequence-with-filter/59399 "2022-08-02T13:04:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tokijh](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tokijh/32/18652_2.png) [@tokijh](https://forums.swift.org/u/tokijh)\
**Post date:** [August 2, 2022, 1:04pm UTC](https://forums.swift.org/t/lazy-sequence-with-filter/59399/1 "2022-08-02T13:04:03Z")

</div>

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

### Code

```swift
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

```swift
map1 0
filter 0
map2 0
0

```

### Result

```swift
map1 0
map2 0
0

```

### Question

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

### Swift version

```swift
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

```

---

<div class="post-metadata">

**Author:** ![cukr](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/cukr/32/889_2.png) [@cukr](https://forums.swift.org/u/cukr)\
**Post date:** [August 2, 2022, 1:55pm UTC](https://forums.swift.org/t/lazy-sequence-with-filter/59399/2 "2022-08-02T13:55:31Z")

</div>

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

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

```

will print

```swift
map1 0
filter 0
map1 0
map2 0
0

```
