Why is there a `sort()` but no `sorted()` method on `OrderedDictionary` and `OrderedSet`?

I can’t really think of a reason why this isn’t offered by the OrderedCollections package. There are in-place sort() (see the documentation) methods for this, so the behavior is well-defined. The only thing I can think of is that it discourages unintentional copies of the underlying buffers, but that same argument would apply to the collections in the standard library and that doesn’t prevent it from having these methods.

So is there a reason I’m not seeing? Or is this just not (yet?) implemented?

This is only a documentation problem. It's not actually missing; it just uses default implementations.

1 Like

The documentation is here: sorted

The unfortunate thing with the default sorted() is that it returns [Element] and not OrderedSet<Element> and OrderedDictionary<Key, Value>, respectively. In this case, those would be very useful to have.

To achieve that, you're of course free to shadow the Sequence extension methods with your own ones like the code below, but it would be nice if these were part of the Collections library already[1]:

extension OrderedSet {
  func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Self {
    var copy = self
    try copy.sort(by: areInIncreasingOrder)
    return copy
  }
}

extension OrderedSet where Element: Comparable {
  func sorted() -> Self {
    var copy = self
    copy.sort()
    return copy
  }
}

…etc. for OrderedDictionary.


  1. …Similarly to how we already have a Self-returning filter(_:) overload defined for both OrderedSet and OrderedDictionary. ↩︎

1 Like

Thanks everybody, this was helpful! I don’t know how I missed the default Sequence implementation (either in the docs or in code), but as @pyrtsa mentioned, this doesn’t really do what I wanted, i.e. return a copy that is sorted. I’m already using the exact shadowing implementation mentioned above to work around this.

The fact that there already is a Self-returning overload of filter(_:) is a really good point. I opened open an GitHub issue asking about adding such overloads of sorted(): Adding `Self`-returning overload of `sorted()` for `OrderedDictionary` and `OrderedSet`? · Issue #477 · apple/swift-collections · GitHub

1 Like

Update: There’s some more historical context and future outlook in the GitHub issue now: Adding `Self`-returning overload of `sorted()` for `OrderedDictionary` and `OrderedSet`? · Issue #477 · apple/swift-collections · GitHub

2 Likes