Scott Zhu Scott Zhu - 3 months ago 8
iOS Question

Swift Dictionary sorted keys extension

I'm using a Dictionary's keys as the

of my
. The Dictionary's type is
[String: [Question]]

The problem is that the array returned from
is not a sorted array, but I want it to be sorted. Create a function to sort the keys array could be a solution, but it's not decent enough for me, because you have to call that function every time you access the keys.

One idea came out of my mine is, to make an extension of Dictionary, something like this,

extension Dictionary where Key: StringLiteralConvertible {
var sortedKeys: [String] {
get {
return keys.sort{ $0.0 > $1.0 }

But it tells me that "Type is expression is ambiguous without more context". Can anyone tell me if this is possible?

extension Dictionary where Key: Comparable {
    var sortedKeys: [Key] {
        get {
            return keys.sort{ $0 > $1 }
  • To use >, Key needs to be Comparable. (This ordering is what you want? You use < for ascending order.)

  • This extension works for Dictionary where Key may not be String.

  • In keys.sort, $0 and $1 are of type Key, not (Key, Value).