[swift-evolution] C-style For Loops

Michel Fortin michel.fortin at michelf.ca
Sun Dec 6 21:16:35 CST 2015


Le 6 déc. 2015 à 21:45, Kevin Lundberg <kevin at klundberg.com> a écrit :

>> As it was pointed out earlier, converting to a while loop requires duplication of the "increment" part of the loop everywhere there is a `continue` inside the loop.
> This is not necessarily true. `defer` could be used at the top of the
> while loop scope to increment whenever the loop turns. The after-fixit
> example you gave can be written like so:
> 
> do {
> 	var i = 10
> 	while i >= 0 {
> 		defer { i -= 1 }
> 		if i == 5 {
> 			continue
> 		}
> 		do {
> 			var j = 100;
> 			while j >= 0 {
> 				print("\(i) \(j)")
> 				j -= 2
> 			}
> 		}
> 	}
> }

It won't matter that you use defer *in this particular case* because the "i -= 1" statement has no side effects, and nothing appears like it can throw in the loop body. But you can't assume this will always be the case, so the fixit shouldn't be allowed to change the semantics like that.

(As I tried to point out in the last sentence of the paragraph you quoted.)


-- 
Michel Fortin
michel.fortin at michelf.ca
https://michelf.ca



More information about the swift-evolution mailing list