Is a set a sequence?

The problem is that since iteration implies ordering, even if it is an implementation-driven ordering, separating those protocols will just have people dump their so-called unordered types into an array, and proceed with their tasks.

Just like they used to do, in the past:

Look at Objective-C NSSet. Its "unordered" smell is strong: it has no firstObject property, like NSArray, but instead anyObject. Much unordered! Of course, the illusion breaks as soon as you see that NSSet conforms to NSFastEnumeration (meaning it has its iteration order just like Swift sets). And, of course, it has the allObjects method which returns the set elements in an NSArray, because, come on, we sometimes want to leave the "unordered" game and do some actual work.

Enters Swift, a protocol-oriented language.

Protocol-oriented programming destroys the little game that NSSet was playing, the "unordered myth". You can no longer pretend that you are unordered when you are iterable. As soon as you have makeIterator(), you get all the methods that you can build on top of the iteration order. That's why Swift sets have prefix(while:), despite all teachers claiming that a Set is "unordered".

Oh, and we no longer have to consume memory by creating an ad-hoc array, like -[NSSet allObjects] when we want to break the unordered illusion, and actually use the iteration order of the set. That's pretty cool, IMHO.

The unordered set myth has been destroyed by POP.

7 Likes