[swift-evolution] [Review] SE-0007 Remove C-style for-loops with conditions and incrementers
thorsten at portableinnovations.de
thorsten at portableinnovations.de
Thu Dec 10 12:20:46 CST 2015
Nice review!
> Am 10.12.2015 um 18:16 schrieb Michel Fortin via swift-evolution <swift-evolution at swift.org>:
>
> 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 ...
> }
> }
That is indeed quite ugly because of (a) the need to check for the first iteration in case of continue and (b) having the condition as guard within the loop and not as while-condition.
Another alternative using a while-loop might be extracting the loop body into a function (still not very nice but at least without checking for the first iteration and having the looping condition in its proper place):
do {
func body(i: Int, _ j: Int) {
if i % 2 == 0 { return } // simulating continue
print (i, j)
}
var i = 10
var j = 20
while (i > 0 && j > 0) {
body(i, j)
i -= 1
j -= 2
}
}
A nicer alternative would actually be the for-in loop:
for (i, j) in zip(10.stride(to: 0, by: -1), 20.stride(to: 0, by: -2)) {
if i % 2 == 0 { continue }
print(i, j)
}
The problem here is that the parameter „to:“ of stride() is not named very intuitively. Its alternative „through:“ is easier to understand.
Maybe „to:“ should be renamed to „towards:“ or something like that.
-Thorsten
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151210/358410a4/attachment.html>
More information about the swift-evolution
mailing list