简体   繁体   中英

Swift: Sort Dictionary of Number Strings

I have a Dictionary of number String that looks like this:

let comph : [String : [String : String]] = [
             "1":["title" : "first title"], 
             "2":["title" : "second title"],
             "10": ["title" : "last title"]
             ]

Then when I sort my Dictionary using comph.sort { $0.0 < $1.0 } I get this:

let sortedComph = comph.sort { $0.0 < $1.0 }
print(sortedComph) //["1":["title" : "first title"],"10": ["title" : "last title"],"2":["title" : "second title"]]

How can I sort the Dictionary so that it returns the keys in numerical order?

eg: ["1":["title" : "first title"],"2":["title" : "second title"],"10": ["title" : "last title"]]

Thanks'

Dictionaries in Swift, by definition, are unsorted collections. You'll need to use some other type if you want to maintain order.

But, it looks like this guy wrote an OrderedDictionary in Swift, if you're interested:

Learning Swift: Ordered Dictionaries

Or, a quick n' dirty solution would be to extract the keys to an array, sort those, then iterate over the array and do a dictionary lookup using the keys.

if you want you could have an array of structure representing your data

struct Model
{
  var key:String!
  var title:String!
  // etc...
}

Then declare the array of that structure:

     var arrayOfStructure = [Model]()

Then you sorted it

The sortedComph constant in your example is no longer a dictionary, but an array of (key, value) tuples. The problem you're running into is that when sorting strings, the comparison is done without treating the strings as numeric values. That's what you need to fix.

One way to handle this is by creating Int? instances from your strings in your comparison function:

let sortedComph = comph.sort { Int($0.0) < Int($1.0) }
// [("1", ["title": "first title"]), ("2", ["title": "second title"]), ("10", ["title": "last title"])]

That way the resulting array will be sorted by the integer value of what's in the string keys. Any non-Integer keys will be grouped at the beginning of the list, since that's how nil sorts.

The more robust way is probably to use the NSString.compare(:options:) method:

let sortedComph = comph.sort {
    ($0.0 as NSString).compare($1.0, options: .NumericSearch) == .OrderedAscending
}
// [("1", ["title": "first title"]), ("2", ["title": "second title"]), ("10", ["title": "last title"])]

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