Pitch: "while" clause on for-loops


(Jacob Bandes-Storch) #1

Currently, for-loops admit a "where" clause:

    for x in seq *where* cond {
        ...
    }

    behaves like

    for x in seq {
        if !cond { continue }
        ...
    }

I'd be interested in a "while" clause:

    for x in seq *while* cond {
        ...
    }

    would behave like

    for x in seq {
        if !cond { break }
        ...
    }

This is one area where C-style for-loops would have provided a clean
solution (combining multiple conditions with &&), but once they're removed
any extra conditions will have to move inside the loop.

Pros:
- It's a simple way to express a common piece of control flow that
otherwise requires negation and another set of braces.
- Its meaning is easy to understand.

Cons:
- It's a new feature.
- Naming might cause confusion with while-loops.

Open questions:
- How/could it be combined with "where" clauses? Would order matter?
- Does anyone else care?

Thanks,
Jacob


(Chris Lattner) #2

My 2c: it is adding complexity and potential for confusion for very little gain. Also, “where” and “while” are structurally different, because while isn’t a modifier that occurs in many other places. Adding “where” to for loops was justified by a push to improve pattern matching in swift.

-Chris

···

On Dec 31, 2015, at 12:42 AM, Jacob Bandes-Storch via swift-evolution <swift-evolution@swift.org> wrote:

Currently, for-loops admit a "where" clause:

    for x in seq where cond {
        ...
    }

    behaves like

    for x in seq {
        if !cond { continue }
        ...
    }

I'd be interested in a "while" clause:

    for x in seq while cond {
        ...
    }

    would behave like

    for x in seq {
        if !cond { break }
        ...
    }

This is one area where C-style for-loops would have provided a clean solution (combining multiple conditions with &&), but once they're removed any extra conditions will have to move inside the loop.

Pros:
- It's a simple way to express a common piece of control flow that otherwise requires negation and another set of braces.
- Its meaning is easy to understand.

Cons:
- It's a new feature.
- Naming might cause confusion with while-loops.

Open questions:
- How/could it be combined with "where" clauses? Would order matter?
- Does anyone else care?