//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.
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.
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.
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