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

Michel Fortin michel.fortin at michelf.ca
Fri Dec 11 08:45:50 CST 2015

Le 11 déc. 2015 à 6:20, David Waite <david at alkaline-solutions.com> a écrit :

> Defer might be appropriate in some cases. It might not be appropriate in others. Why are we trying to guess the programmer’s intentions?

Defer is geared to do cleanup work, work that must not be avoided even when an exception is thrown. If one day Swift becomes capable of properly unwinding the stack when a C++ or Objective-C exception is thrown, defer's performance characteristics might change a little bit. More code will be added to handle the exception case, and an entry will have to be added to the unwind table so the unwind mechanism can call that increment that should not be called in the first place.

That's not supported right now, but the Swift team at Apple has obviously been thinking about it.

All this illustrates that defer is the wrong mechanism for implementing a loop. Add that the semantics are slightly wrong anyway, the only remaining thing in its favor is that it's more syntactically convenient. Well, I think that's a problem. It must not be syntactically more convenient. Let's not encourage the use of defer to implement a loop.

Keeping the C-style for loop would help avoid defer being used in that situation. Adding an optional increment clause to a while loop could do the trick too. There might be better solutions. But please, not defer.

Michel Fortin
michel.fortin at michelf.ca

More information about the swift-evolution mailing list