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

Kevin Lundberg kevin at klundberg.com
Mon Dec 7 20:04:45 CST 2015


For throw, if incrementing i has no external side effects, then there shouldn’t be any issue since i will be thrown away anyways when the error is thrown. 

For break, it can be considered dangerous, but if your while loops are written semantically like the old c-style for loop, the counter shouldn’t be used outside the scope of the loop anyways. If that matters to whomever may write code like this, then manual incrementing at each point where loop scope breaks is necessary (though I imagine such cases are likely rare).
--
Kevin Lundberg

> On Dec 7, 2015, at 8: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!!!
> 		}
> 	}
> 
> 
> -- 
> Michel Fortin
> michel.fortin at michelf.ca <mailto:michel.fortin at michelf.ca>
> https://michelf.ca <https://michelf.ca/>
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151207/fd7c243c/attachment.html>


More information about the swift-evolution mailing list