[swift-evolution] [Review] SE-0007 Remove C-style for-loops with conditions and incrementers
Stephen Celis
stephen.celis at gmail.com
Thu Dec 10 14:13:44 CST 2015
On Thu, Dec 10, 2015 at 12:16 PM, Michel Fortin via swift-evolution <
swift-evolution at swift.org> wrote:
> You can't replace C-style for loops with for-in in the general case. Using
> a "while" loop will always be possible, but also much more verbose. For
> instance, take this loop iterating downward over i and j in lockstep:
>
> for var i = 10, j = 20; i > 0 && j > 0; i -= 1, j -= 2 {
> ... loop body ...
> }
>
> The only fully-compatible while loop that makes sense is this one:
>
> do {
> var i = 10
> var j = 20
> var first = true
> while true {
> if first { first = false }
> else { i -= 1; j -= 2 }
> guard i > 0 && j > 0 else { break }
> ... loop body ...
> }
> }
>
> If the loop body contains a continue, it works. If the loop body mutates
> one of the loop variables, it works. If the loop throws, it works. If the
> outer scope has a variable with the same name, it works! There is no code
> duplication. But oh boy, the boilerplate!
>
Can't you do the following?
var i = 10, j = 20; while i > 0 && j > 0 { defer { i -= 1; j -= 2 }
// ...
}
I adjusted the formatting to more closely match the C-style for loop, so if
you were to use a more Swift-y style, it would be slightly more verbose.
Stephen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151210/88281597/attachment.html>
More information about the swift-evolution
mailing list