[swift-evolution] C-style For Loops

Tyler Fleming Cloutier cloutiertyler at aol.com
Sun Dec 6 15:13:43 CST 2015

> Lowered Readability and Maintainability
> I have aesthetic reasons for disliking the for-loop. The C-style loop is harder to read especially for those not coming from C-style languages, easier to mess up at edge conditions, and is commonly used for side-effects which, in a language focused on safety, is not a feature to be encouraged. 
> For example, one side effect that was mentioned on-list yesterday was the incrementor, which is guaranteed in C-style to execute late:
> Roland King writes:
> for var floatingThing = start ; floatingThing <= end ; floatingThing += delta
> {
> 	// more than a few lines of code with early escape continues
> }
> shows intent of the loop very clearly, start, condition and increment all together at the top, and however you loop you always execute the increment part of the statement. Convert that to a while(), if you have a continue in the body, you have a good chance of not incrementing at all, or duplicating the increment code before every continue. So you can’t always nicely turn for into while. I second the point below about the loop variable being local to the for as well, I also like that. 
> Late incrementor management is a feature that can be mimicked with defer, as pointed out by several other list members.

Defer wouldn’t accomplish the exact same behavior because it would run if an exception was thrown, which is not the same as the last clause of a for loop, but perhaps is close enough.

The only other concern I would have is not being able to scope my variables to the loop. I didn’t see it addressed, but perhaps its not very important in the end anyway.

Something like the following might be nice to scope the variable exclusively to the loop.

for var x = 0 while (someCondition()) {
	// code
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151206/01429aab/attachment.html>

More information about the swift-evolution mailing list