Is a set a sequence?

So we can do stupid things with Set.reversed ;-).
Most programming languages and especially Swift try to protect us from our own stupidity, and as elementsEqual demonstrated, that didn't work that well in this case.

To not only blame Set all the time I have another example:
Someone wrote a program for a sports and included a small new routine to print out the winners.

struct Marathon {
	var succesfulContestants: Array<(String, TimeInterval)>
 }
    // real Marathon type is bigger and defined elsewhere

func printPodium(of marathon: Marathon) {
	marathon.succesfulContestants.prefix(3).forEach {
		print("Contestant: \($0.0) (\($0.1 / 3600))")
	}
}

Thanks to autocompletion, it's very easy to write this down, and maybe there's even a unit test that said everything is ok.
Now, some time later, someone else has to change the software, and he has to add a feature so that he can easily look up the time for each runner.
So, he makes a little change:

var succesfulContestants: Dictionary<String, TimeInterval>

The compiler doesn't complain, the unit tests are green, but the developer silently broke an important functionality.

So, the question shouldn't be "is it harmful that Dictionary conforms to Sequence", but rather "is there any downside when I can only iterate through Dictionary's contents, and not call methods that depend on a meaningful order?"

2 Likes