[swift-evolution] Review for: Remove C-style for-loops with conditions and incrementers

Joe Groff jgroff at apple.com
Mon Dec 7 20:03:20 CST 2015


> On Dec 7, 2015, at 5:58 PM, Michel Fortin via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Le 7 déc. 2015 à 20:29, Kevin Ballard via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> a écrit :
> 
>> On Mon, Dec 7, 2015, at 01:07 PM, Dmitri Gribenko via swift-evolution
>> wrote:
>>> Another concern of mine is the equivalent of C-style for loops with
>>> 'continue' statements in them.  The only equivalent based on 'while' I
>>> can think of duplicates the increment portion of the loop.
>> 
>> As has been pointed out in other threads on this topic, you can use a
>> defer statement to avoid duplicating the increment portion:
>> 
>> var i = initial
>> while cond(i) {
>>   defer { i = increment(i) }
>>   // ...
>>   if frob {
>>       continue // defer will execute
>>   }
>> }
> 
> Which is a dangerous substitute, because it also does the wrong thing with break and throw:
> 
> 	var i = initial
> 	while cond(i) {
> 		defer { i = increment(i) }
> 		// ...
> 		if frob {
> 			continue // defer will execute
> 		} else if blob {
> 			break // defer will execute!!!
> 		} else if plob {
> 			throw MyError // defer will execute!!!
> 		}
> 	}


A more accurate (but not particularly pretty) substitution would be to perform the increment as part of the condition:

while { i = increment(i); return cond(i) }() {
}

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151207/3a55a745/attachment.html>


More information about the swift-evolution mailing list