简体   繁体   中英

Swift : Sort array by natural order

I'm having an dictionary with order here:

var pickerData = [
    "en":"abc",
    "jp":"xyz",
    "fr":"gya",
    "zh-CN":"uio"]

But when i println() pickerData.keys.array , the order is not like thit. I want to sort pickerData.keys.array by order above. Is it posible?

Dictionaries are not an ordered data structure. Arrays are. So taking the keys from an unordered data structure will result in an unordered result. You'll need to create your own OrderedDictionary, which isn't that hard to do.

Here is a project with an example of an ordered dictionary: https://github.com/lithium3141/SwiftDataStructures

Here is an article explaining the whole thing if you care for the details: http://timekl.com/blog/2014/06/02/learning-swift-ordered-dictionaries/

This is how you sort array of keys:

let sortedKeys = sorted(pickerData.keys.array, { 
    (s1: String, s2: String) -> Bool in
    return s1 < s2
})

Just replace the return statement to change the sort logic to the one which match your requirements.

To obtain a sorted version of the keys array, taking into account that it's an immutable array, you have to:

  • copy to a mutable variable
  • sort in place using the sort method

This is the code:

var array = pickerData.keys.array as [String]
array.sort(<)

Now array is sorted alphabetically. The reason why a copy of the keys array is needed is that sort operates in place, which is obviously not possible on an immutable array.

Since Swift 4 and 5 this has got a lot easier:

for mySortedKey in pickerData.keys.sorted() {
    [....]
}

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