Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a paragraph about pack iteration [SE-0408] #206

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions TSPL.docc/ReferenceManual/Statements.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,19 @@ and a `continue` statement and is discussed in <doc:Statements#Break-Statement>
A `for`-`in` statement allows a block of code to be executed
once for each item in a collection (or any type)
that conforms to the
[`Sequence`](https://developer.apple.com/documentation/swift/sequence) protocol.
[`Sequence`](https://developer.apple.com/documentation/swift/sequence) protocol, or in a value parameter pack.

A `for`-`in` statement has the following form:

```swift
for <#item#> in <#collection#> {
for <#item#> in <#expression#> {
<#statements#>
}
```

The `makeIterator()` method is called on the *collection* expression
to obtain a value of an iterator type --- that is,
a type that conforms to the
If the *expression* of a `for`-`in` statement is a collection *expression*, the
`makeIterator()` method is called on it to obtain a value of an iterator type
--- that is, a type that conforms to the
[`IteratorProtocol`](https://developer.apple.com/documentation/swift/iteratorprotocol) protocol.
The program begins executing a loop
by calling the `next()` method on the iterator.
Expand All @@ -93,6 +93,16 @@ and then continues execution at the beginning of the loop.
Otherwise, the program doesn't perform assignment or execute the *statements*,
and it's finished executing the `for`-`in` statement.

The *expression* of a `for`-`in` statement may also be a pack expansion
*expression*. In this case, on the *i*th iteration, the type of *item* is the
*i*th type parameter in the type parameter pack being iterated over. The value
of *item* is the pattern type of *expression*, with each captured type
parameter pack replaced with an implicit scalar type parameter with matching
requirements. The *expression* is evaluated once at each iteration, instead of
`n` times eagerly, where `n` is the length of the packs captured by the
pattern. The program will continue executing *statements* while the total
length of the packs captured by the pattern isn't reached.

> Grammar of a for-in statement:
>
> *for-in-statement* → **`for`** **`case`**_?_ *pattern* **`in`** *expression* *where-clause*_?_ *code-block*
Expand Down