TomSawyer
TomSawyer

Reputation: 3820

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?

Upvotes: 3

Views: 1235

Answers (4)

bownie
bownie

Reputation: 1618

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

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

Upvotes: 0

Antonio
Antonio

Reputation: 72760

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.

Upvotes: 1

Greg
Greg

Reputation: 25459

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.

Upvotes: 1

wottle
wottle

Reputation: 13619

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/

Upvotes: 2

Related Questions