Why no dict.sort()

//Value of type '[String : Int]' has no member 'sort'; did you mean 'sorted'?

why can't sort() dictionary directly. and the sorted() result is even not dictionary. what's the magic reason, principle & philosophy behind the scene.

this is wrong. data structures, containers or collections are existed to be manipulated. this includes sort & search.

will swift dictionary has sort() at last.

sort wouldn't make sense to Dictionary. With Dictionary, you check if you have a value associated with a given key, not where the value is–it has no sense of order (what comes first, second, etc). On the other hand, if you want to sort something, you need to force an order onto it. They're in conflict even at a syntactical level.

That's why sorted returns Array instead; it has notion of order.

Probably a better question to ask is if we will have native OrderedDictionary, or OrderedSet for that matter.

2 Likes

unordered keys can be sorted based on predicate provided by user. the keys may be the same things in another array.

maybe this is better:
var dict = Dict(order: .order, multikey: .multikey)

swift has only 3 primary collections. but c++ has 4 different kinds of map, that's too much.

You can do that outside of Dictionary. It doesn't aid in the working of Dictionary, so there's no reason to put them in there.

You can create a new type that does what you just said.

struct SortedDictionary<Key, Value> where ... {
  var dict: [Key: Value]
  var sortedKeys: [Key]
  ...
}

There's no point in trying to put everything under the same umbrella type. Choice of ordered-ness, multi-key support, all easily leads to different data structure, each has its own in-memory storage, read/write code, performance guarantee, etc.

4 Likes

If you want the contents of a dictionary, sorted, then all you have to do is :

    let dict = [1 : "one", 2 : "two", 3 : "three"]
    
    let sortedDict = dict.sorted { $0.0 < $1.0 } .map { $0 }
    
    let sortedValues = dict.sorted { $0.0 < $1.0 } .map { $0.1 }
    
    let reverseSortedValues = dict.sorted { $0.0 > $1.0 } .map { $0.1 }

In that way you don't incur any overhead for sorting until you actually need the sorted dictionary and you have the flexibility of being able to change the sort as and when required.

Of course, sortedDict is actually an array of tuples, each of which contain a key and a value member, which, if you look at the definition of Dictionary, is exactly what an unsorted Dictionary is :wink:

Thanks Joanna