简体   繁体   中英

Swift Dictionary sorted keys extension

I'm using a Dictionary's keys as the datasource of my tableview . The Dictionary's type is [String: [Question]] .

The problem is that the array returned from Dictionary.keys 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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM