Dictionary wrong order - JSON

I am trying to create a dictionary that I can make into a JSON formatted object and send to the server.

Example:

    var users = [
[
"First": "Albert", 
"Last": "Einstein", 
    "Address":[
        "Street": "112 Mercer Street",
        "City": "Princeton"]
],
[
"First": "Marie", 
"Last": "Curie", 
    "Address":[
        "Street": "108 boulevard Kellermann",
        "City": "Paris"]]
]

I use this function

func nsobjectToJSON(swiftObject: NSObject) -> NSString {
    var jsonCreationError: NSError?
    let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(swiftObject, options: NSJSONWritingOptions.PrettyPrinted, error: &jsonCreationError)!
    var strJSON = NSString()

    if jsonCreationError != nil {
        println("Errors: \(jsonCreationError)")
    }
    else {
        // everything is fine and we have our json stored as an NSData object. We can convert into NSString
        strJSON =  NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
        println("\(strJSON)")
    }
    return strJSON
}

But my result is this:

[
  {
    "First" : "Albert",
    "Address" : {
      "Street" : "112 Mercer Street",
      "City" : "Princeton"
    },
    "Last" : "Einstein"
  },
  {
    "First" : "Marie",
    "Address" : {
      "Street" : "108 boulevard Kellermann",
      "City" : "Paris"
    },
    "Last" : "Curie"
  }
]

Problem: why is the last name last? I think it should be above address. Please let me know what I am doing wrong with the NSDictionary for this to come out wrong. Any help would be very much appreciated - thank you.


Solution 1:

To post what has already been said in comments: Dictionaries are "unordered collections". They do not have any order at all to their key/value pairs. Period.

If you want an ordered collection, use something other than a dictionary. (an array of single-item dictionaries is one way to do it.) You can also write code that loads a dictionary's keys into a mutable array, sorts the array, then uses the sorted array of keys to fetch key/value pairs in the desired order.

You could also create your own collection type that uses strings as indexes and keeps the items in sorted order. Swift makes that straightforward, although it would be computationally expensive.