[swift-evolution] for-else syntax

Jeremy Pereira jeremy.j.pereira at googlemail.com
Thu Feb 2 05:06:00 CST 2017

> On 1 Feb 2017, at 18:29, Chris Davis via swift-evolution <swift-evolution at swift.org> wrote:
> ah! I forgot about the break semantics, that’s definitely one for the con list.
> I like Nicolas’ solution, clear to read.
>> On 1 Feb 2017, at 18:18, Nicolas Fezans <nicolas.fezans at gmail.com> wrote:
>> I tend to write this kind of treatment the other way around...
>> if names.isEmpty {
>> 	// do whatever
>> } // on other cases I might have a few else-if to treat other cases that need special treament
>> else {
>> 	for name in names {
>> 		// do your thing
>> 	}
>> }

This only works if you know the size of the sequence before you start iterating it. You can, for example, iterate a lazy sequence and calculating its size before iterating it defeats the object.Thus for { … } else { … } where the else block only executes if the for block was never executed does have some utility.

However, I am not in favour adding it. The same functionality can be achieved by counting the number of iterations and testing the count afterwards (or by using a boolean). It takes a couple of extra lines of code and an extra variable, but I think that is a Good Thing. It’s more explicit and (as the Python example shows) there could be hidden subtleties that confuse people if for … else … is badly designed. Also, in many cases, I would argue that treating the zero element sequence differently to the n > 0 element sequence is a code smell. About the only use-case I can think of off the top of my head is UI presentation e.g. “your search didn’t return any results” instead of a blank page.

Talking of Python, Swift is not Python and the argument not to implement a feature because its semantics conflict with the semantics of a similar looking feature in another language is bogus. I don’t see the Python for … else being different (and having looked it up to see what you all were talking about, my opinion is that the Python for … else is a disaster) as being a legitimate con to this cleaner and more logical idea in Swift.


More information about the swift-evolution mailing list