Mimicking mathematical sets or sequences is not the job of a Swift set. Its job is to provide a set of operations, with guaranteed algorithmic complexity, that cover a set of related use cases, and that all together form a "data structure" which happens to be named "set" because that data structure looks like a mathematical set:
- uniqued elements
- containment test
- element insertion
- element removal
- iteration
An interesting divergence with mathematical sets is that a Swift set requires its elements to conform to Hashable, when a mathematical set would have been OK with Equatable (I mean a way to distinguish different elements). That's because Swift set wants its methods to have a low complexity. This divergence is interesting because it's a reminder that we're not talking mathematics, here.
An interesting convergence with mathematical sets and sequences is that a Swift set can be iterated. In maths, you can write "let F = { x in E | x * 2 }", or "let V(n) = U(n) + 1". OK, that's not really the same iteration as the iteration of a Swift set. But none of those objects really want to hide their contents (at least when they're countable).
When you iterate a Swift set, you materialize an ordering. Let's call it the iteration order of the set.
But can I? Does this "iteration order" even exist? Is it a stable property of a set? I mean, can I write the assertions below?
let s = Set(...)
assert(s.elementsEqual(s))
assert(Array(s) == Array(s))
if let i = s.index(where: predicate) {
assert(predicate(s[i]))
}
The shy answer is: WHY NOT, as long as the Swift set keeps on fulfilling its job at being an implementation of the data structure that is called "set".
The pragmatic answer is: YES OF COURSE, because preventing users from relying on those assertions would 1. require to increase the complexity of the Swift Set implementation, and 2. make the Swift Set a painful data structure to work with.
The consequence is that a Swift set is an ordered data structure. You can't control this order. But you can't say it does not exist. And it's a hard fact.
The sentence "sets are unordered" is a teacher's sentence. It's a way to tell that one can't control the set order, and should not, generally, rely on it. You don't know in which order elements will be outputted in for x in set { print(x) }. It may change on the next program execution. It may be different for two sets that contain the same elements. I find it very funny that the word "unordered" is used to describe... an ordering. It should not be taken too seriously.