# SE-0231 — Optional iteration

**URL:** <https://forums.swift.org/t/se-0231-optional-iteration/16737>\
**Category:** Proposal Reviews\
**Created:** [October 5, 2018, 5:07pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737 "2018-10-05T17:07:09Z")\
**Posts on this page:** 20\
**Page:** 10

<div class="post-metadata">

**Author:** ![gregtitus](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gregtitus/32/4274_2.png) [@gregtitus](https://forums.swift.org/u/gregtitus)\
**Post date:** [October 10, 2018, 4:08pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/182 "2018-10-10T16:08:52Z")

</div>

(Edit to add: looks like you also need

```swift
func ??<S>(lhs: S?, rhs: S) -> S where S : Sequence, S: ExpressibleByArrayLiteral {
  switch lhs {
  case .some(let s):
    return s
  case .none:
    return rhs
  }
}

```

In order to make sure existing sequences that are expressible by `[]` aren't accidentally wrapped in an `AnySequence`.)

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [October 10, 2018, 4:29pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/183 "2018-10-10T16:29:40Z")

</div>

> [@Joe\_Groff](#):
>
> I would be interested in seeing more hard evidence of this sort from anyone else willing to spend some time mining their own private Swift codebases

I did a quick check of the [compatibility suite](https://github.com/apple/swift-source-compat-suite). It was a simple regex + eyeball so I think it avoids false positives but will probably be off +- a few.

I could see 20 examples of `for` with `?? []` and 55 examples of `if let` immediately followed by use in a `for`. Overall 24 projects used one of these patterns, so just over a quarter of the projects.

edit: adding in `?.forEach`, of which there are 15 occurrences.

Anecdotally, this is a pretty high occurrence rate based on searches for similar patterns for other reviews I've done in the past.

---

<div class="post-metadata">

**Author:** ![Scott](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/scott/32/23832_2.png) [@Scott](https://forums.swift.org/u/Scott)\
**Post date:** [October 10, 2018, 4:36pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/184 "2018-10-10T16:36:02Z")

</div>

Not sure if you looked at this: did the if let cases have any else condition?

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [October 10, 2018, 4:46pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/185 "2018-10-10T16:46:41Z")

</div>

I tried to spot and exclude those. Also there were quite a few cases to exclude where the `let` was used as an argument to the sequence-producing function rather than the iteree itself, which I also excluded, though strictly speaking, if we had an optional `for` syntax, that would allow `map` to be used in those cases.

---

<div class="post-metadata">

**Author:** ![gregtitus](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gregtitus/32/4274_2.png) [@gregtitus](https://forums.swift.org/u/gregtitus)\
**Post date:** [October 10, 2018, 5:28pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/186 "2018-10-10T17:28:58Z")

</div>

> [@Joe\_Groff](#):
>
> Personally, I'd like to see deeper analysis of the "Is this problem important to solve" angle, and doing more data analysis like what @algal has provided would be very interesting.

In our codebase (about 100k lines of Swift mixed in with about 1M lines of ObjC) there are 13 matches for @algal's `for _ in _ ?? []` regex. 6 of them involve optional chaining, and all of those are related to an optional `NSView`/`UIView` (e.g. `for subview in superview?.subviews ?? []`).

Our in-house Swift style is generally to `guard` exclude optionals as soon as is practical and avoid dealing with them. I even notice that there are at least 5 places where it might have been natural to use optional chaining with sequences (outside of a `for`) and I see constructions like `(getOptionalSequence() ?? []).map({...}).filter({...})` instead.

---

<div class="post-metadata">

**Author:** ![Scott](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/scott/32/23832_2.png) [@Scott](https://forums.swift.org/u/Scott)\
**Post date:** [October 10, 2018, 6:02pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/187 "2018-10-10T18:02:58Z")

</div>

> [@Joe\_Groff](#):
>
> As review manager, I would be interested in seeing more hard evidence of this sort from anyone else willing to spend some time mining their own private Swift codebases

Using @algal 's strategy:

Our codebase has ~70,000 lines of swift code, we match 11 times for the regex looking for `if let` statements followed by `for` loops. 2 is the result of poor representation of data, resulting in conditional casting, the rest could have used `?.forEach` or `?? []` (though using the `?.forEach` on some of those would involve unfortunate parenthesis).

---

<div class="post-metadata">

**Author:** ![michelf](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/michelf/32/1180_2.png) [@michelf](https://forums.swift.org/u/michelf)\
**Post date:** [October 10, 2018, 6:22pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/188 "2018-10-10T18:22:07Z")

</div>

I have 56 instance of `for x in sequenceExpression ?? []` in my code base, roughly 10% of all the `for` loops. Half of those come from XML parsing code (where you must always worry about parts of the structure being missing). Things like this:

```swift
for noteElement in unitElement.first("notes")?.all("note") ?? [] {
    // do something with the note
}

```

Currently the filters for XML elements of interest all return eagerly constructed arrays, so using `sequenceExpression ?? []` works nicely. It'd be better to return lazy sequences, but then all the loops would need to be wrapped like this:

```swift
if let notesElement = unitElement.first("notes") {
    for noteElement in notesElement.all("note") {
        // do something with the note
    } 
}

```

Also, trying to mix `?? []` with lazy sequences could trigger the [the trap unearthed by @Ben\_Cohen](https://forums.swift.org/t/se-0231-optional-iteration/16737/132), which could make the algorithm eager again without notice. That's a concern, although it's not anything specific to `for` loops.

**Edit:** code base is about 60k lines of Swift code.

---

<div class="post-metadata">

**Author:** ![JhonnyBillM](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jhonnybillm/32/15739_2.png) [@JhonnyBillM](https://forums.swift.org/u/JhonnyBillM)\
**Post date:** [October 10, 2018, 6:29pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/189 "2018-10-10T18:29:27Z")

</div>

Using [**@algal**](https://forums.swift.org/u/algal) 's strategy:

LOC: `47,057`

Matches: `3` [All of them use an `else` case].

Pods matches: `9` [5 of them use an `else` case].

**`Total: 12 matches.`**  
8 of them using `else` case.

Note: I don't think the change it's worth it.

---

<div class="post-metadata">

**Author:** ![Michael\_Ilseman](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/michael_ilseman/32/44640_2.png) [@Michael\_Ilseman](https://forums.swift.org/u/Michael_Ilseman)\
**Post date:** [October 10, 2018, 6:38pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/190 "2018-10-10T18:38:23Z")

</div>

Also, some overlays and source kit:

> <https://github.com/apple/swift/blob/9544a00b46d5be9c957ebb045bfaf1dc176074ba/stdlib/public/SDK/Network/NWConnection.swift#L377>

> <https://github.com/apple/swift/blob/9544a00b46d5be9c957ebb045bfaf1dc176074ba/stdlib/public/SDK/Network/NWParameters.swift#L131>

> <https://github.com/apple/swift/blob/9544a00b46d5be9c957ebb045bfaf1dc176074ba/stdlib/public/SDK/Network/NWParameters.swift#L152>

> <https://github.com/apple/swift/blob/9544a00b46d5be9c957ebb045bfaf1dc176074ba/tools/SourceKit/tools/swift-lang/SourceKitdRequest.swift#L142>

My memory is that I reach for this pattern frequently, but I don't currently have any code on-hand that does this.

---

<div class="post-metadata">

**Author:** ![duan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/duan/32/40252_2.png) [@duan](https://forums.swift.org/u/duan)\
**Post date:** [October 10, 2018, 7:56pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/191 "2018-10-10T19:56:24Z")

</div>

In 255948 lines of just Swift code, _excluding_ empty lines and comments (collected by `cloc`):

Occurrence of @algal's regex

```swift
if[:space:]*let[:space:]*\w+[:space:]*=[:space:]*.*[:space:]*\{[:space:]*for

```

**5**

Occurrence of `for .+ in .+ ?? \[\]`: **14**

---

<div class="post-metadata">

**Author:** ![anandabits](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anandabits/32/355_2.png) [@anandabits](https://forums.swift.org/u/anandabits)\
**Post date:** [October 10, 2018, 8:02pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/192 "2018-10-10T20:02:32Z")

</div>

In a 500k+ line codebase I have access to I see 210 results for this regex. A lot of this code was written by people not familiar with Swift idioms so probably half of those fall into the stored optional array anti-pattern, however many of them are the result of optional chains and other reasonable code patterns.

---

<div class="post-metadata">

**Author:** ![JoeyKL](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joeykl/32/3140_2.png) [@JoeyKL](https://forums.swift.org/u/JoeyKL)\
**Post date:** [October 10, 2018, 8:27pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/193 "2018-10-10T20:27:48Z")

</div>

Apologies if someone has mentioned this before, but why can't we just add `.orEmpty()` like Kotlin has?

```
extension Optional where Wrapped: Sequence {
    func orEmpty() -> AnySequence<Wrapped.Element> {
        switch self {
        case nil:
            return AnySequence(EmptyCollection())
        case .some(let s):
            return AnySequence(s)
        }
    }
}

let nilAsCanBe: [Int]? = nil

for i in nilAsCanBe.orEmpty() {
    // ...
}

```

Trivial to implement, easy to read, no language changes, no further overloading `?`. (Bikeshed the name all you want.)

Edit: Fixed very sloppy non-compiling code.

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [October 10, 2018, 8:34pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/194 "2018-10-10T20:34:30Z")

</div>

Yeah, this was one of the possibilites that came up, which I listed in my [summary](https://forums.swift.org/t/se-0231-optional-iteration/16737/178). I added a link to the summary into the original post to hopefully make this more discoverable.

---

<div class="post-metadata">

**Author:** ![Ling\_Wang](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ling_wang/32/2691_2.png) [@Ling\_Wang](https://forums.swift.org/u/Ling_Wang)\
**Post date:** [October 10, 2018, 8:40pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/195 "2018-10-10T20:40:41Z")

</div>

Interesting. It makes me wonder why Sequence.reversed() returns an array in the first place. Why not return a Sequence?

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [October 10, 2018, 8:48pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/196 "2018-10-10T20:48:00Z")

</div>

The issue AIUI is that there are overloads that do both, and `?? []` contextually leaves only the array-producing form as a possibility.

---

<div class="post-metadata">

**Author:** ![Jens](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jens/32/12903_2.png) [@Jens](https://forums.swift.org/u/Jens)\
**Post date:** [October 10, 2018, 9:08pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/197 "2018-10-10T21:08:54Z")

</div>

The pattern `.+ in .+ \?\? \[\]` produces only 1 true positive:

```swift
for e in n.geometry?.elements ?? [] { … }

```

and many false positives such as:

```swift
for set in a1 { x4.formUnion(set ?? []) }

```

and

```swift
let objs: [TagItem] = selectedTagName.map { selTagName in document.catalog.tagItems.filter { $0.name == selTagName } } ?? []

```

in our 200k line codebase.

And the pattern `if[[:space:]]let[[:space:]]*\w+[[:space:]]*=[[:space:]]*.*[[:space:]]*\{[[:space:]]*for` produces zero matches. I had to double check by removing the last "`for`" which resulted in a lot of matches so for some reason our code base doesn't have a single occurrence of `if let a = b { for`.

---

<div class="post-metadata">

**Author:** ![endofunk](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/endofunk/32/3220_2.png) [@endofunk](https://forums.swift.org/u/endofunk)\
**Post date:** [October 10, 2018, 9:16pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/198 "2018-10-10T21:16:38Z")

</div>

In just over 100K lines of Swift, excluding empty lines and comments (cloc); I found 5 instances using @algal's regex for:

- `if let ... for ...`
- `for ... in ...?? []`

I still don't see the driving need for this; re a few of these instances could fairly easily be avoided.

---

<div class="post-metadata">

**Author:** ![Ling\_Wang](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ling_wang/32/2691_2.png) [@Ling\_Wang](https://forums.swift.org/u/Ling_Wang)\
**Post date:** [October 10, 2018, 9:32pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/199 "2018-10-10T21:32:59Z")

</div>

I only see one returning Array. I mean if Sequence.reversed() returns the same Sequence type(Self)—which feels very natural—the problematic code won't compile at all. There must be good reasons that the current API returns Array instead of Self(same for sorted()), what are they?

---

<div class="post-metadata">

**Author:** ![ben-cohen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ben-cohen/32/296_2.png) [@ben-cohen](https://forums.swift.org/u/ben-cohen)\
**Post date:** [October 10, 2018, 9:39pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/200 "2018-10-10T21:39:08Z")

</div>

To reverse something that doesn't provide iteration from the last to first element (not just sequences, but forward-only collections as well), you must stream all the elements into some kind of storage first, then return them in reverse order. If you're going to do that, it may as well be an array because having an array is a useful thing to have. You could instead return some kind of opaque reversed thing, but that wouldn't help – you still have to allocate memory for all those elements.

---

<div class="post-metadata">

**Author:** ![endofunk](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/endofunk/32/3220_2.png) [@endofunk](https://forums.swift.org/u/endofunk)\
**Post date:** [October 10, 2018, 10:00pm UTC](https://forums.swift.org/t/se-0231-optional-iteration/16737/201 "2018-10-10T22:00:41Z")

</div>

> [@ben-cohen](#):
>
> for i in maybeHugeRange?.reversed() ?? { // doom occurs here

Re your discussion with @Ling_Wang  
That trap seems very specific to the combination of `.?` and `?? []`. Neither of the following IMO would result in this:

- Rust's `unwrap_or`
- Java's ` orElse`
- Scala's `getOrElse`

...and I certainly can't easily recreate that with a similar extension method.

[Previous page](https://forums.swift.org/t/se-0231-optional-iteration/16737.md?page=9)

[Next page](https://forums.swift.org/t/se-0231-optional-iteration/16737.md?page=11)
