Why OrderedDictionary<Int, [Int]> keys are not in order?

    static let primesLastDigits = OrderedDictionary<Int, [Int]>(grouping: sieveOfEratosthenes(1_00)) { prime in
        prime % 10

the keys:

2, 3, 5, 7, 1, 9

Why is 1 not the first?

However, like an Array (and unlike Dictionary ), ordered dictionaries maintain their elements in a particular user-specified order, and they support efficient random-access traversal of their entries.

It maintains the user-specified order (i.e. the order in which they are added to the OrderedDictionary), not the order implied by Comparable (indeed, the keys only need to be Hashable, so that wouldn't even be an option).

1 Like

How to specify this?

It's the order in which they are added to the collection (or in the case of APIs like the initializer here, the order implied by the collection from which it is constructed).


I think a sorted dictionary might fit your use case better than OrderedDictionary. The swift-collections package includes a SortedDictionary implementation on its main branch. (It is based on an in-memory B-tree implementation.)

It isn't yet ready for production use, but it could be useful for experimentation!


I try to use keys:

ForEach(Self.primesLastDigits.keys, id: \.self) { // Generic struct 'ForEach' requires that 'SortedDictionary<Int, [Int]>.Keys' conform to 'RandomAccessCollection'

This works with Dictionary and OrderedDictionary

Hi @lorentey ,
What might be missing from SortedDictionary in order for it to be production ready?

To be quite frank, what’s missing is a use case that would confirm the design, and would drive (and justify the expense of) finalizing and shipping these new container types.

(Keep in mind that swift-collections also has a large backlog of actually production-ready, but still unreleased, container implementations that have been sitting in limbo for several Swift releases.)

1 Like

Since you mentioned them, what’s the ETA on those?

1 Like