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

Michel Fortin michel.fortin at michelf.ca
Mon Dec 7 19:58:01 CST 2015


Le 7 déc. 2015 à 20:29, Kevin Ballard via swift-evolution <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
https://michelf.ca



More information about the swift-evolution mailing list