0

I'm trying to create a Parameter request with Multiple Key Value Dictionary and it's creating perfectly. But every time dictionary is created with random Key - value order. How to Sort or order with respect to Dictionary Keys. Example :

    [
      "mbappdetails": [
"locationdtls": [
          "ipAdress": "100.105.100.6",
          "locationDtl": "NaviMumbai,Maharashtra",
          "longdtl": "73.0152077",
          "latdtl": "19.1112212"
        ],
        "appdtls": [
          "appregflg": "00",
          "appid": "com.mmcompany.nstapp",
          "applversion": "1.0.70",
          "pushnkey": "cVCzsSyxCLr4l5JPElHWLDiNuoQJcbFmRlN5LFWZM9hN5lYYZnJy_4Kvvu2_fAjBXhGxbKpt"
        ],
        "devicedtls": [
          "deviceserial": "ExtEYNBSO8D85KR7DCEIOSHH",
          "devicemodel": "iPod Touch 6",
          "os": "iOS",
          "simflag": "N",
          "devicesdkversion": "12.10",
          "deviceproduct": "iPod Touch 6",
          "deviceid": "XXXXX-A2F5-XXXX-8EAC-XXXXX",
          "devicemake": "iPod touch",
          "rootflg": "N",
          "devicebrand": "APPLE",
          "osVersion": "12.1.4"
        ],
        "channelid": "XXXXXXRRRRRR"
      ],
      "token": "myToken",
      "signcs": "encrypted_dictionary_key_values_with_signature_key"
    ]

Order Should be : channelid,appdtls,devicedtls,locationdtls,token,signcs

Output must be in Dictionary ONLY.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

3 Answers3

3

Unfortunately, the Dictionary data structure was not designed for any sorted storage. However, you can sort the keys and get it in the form of the array.

let dictionary = [
    "A" : [1],
    "Z" : [3],
    "C" : [2]
]

let keysSorted = Array(dictionary.keys).sorted(<)

Then you can iterate over the sorted array and look up dictionary values by keys. Hope it helps!

Krakke93
  • 95
  • 5
  • As I said before dictionary data structure doesn't preserve the order in which the elements are inserted, nor doesn't support any particular order. However, if you need to send the values to a server in a specified order, I suggest writing your own logic to transfer unordered dictionary values into ordered JSON ones. – Krakke93 Apr 19 '19 at 14:10
0

You did not add any code so you can try this: (You can change sign according to your requirement. in Which as-sending or descending order you want)

let sortedDict = YourDictionary.sorted(by: {$0.0 > $1.0})

and if you are trying to call an API then it does not matter in which order params are.

0

You try the below code.

    var dict = ["name" : "Test", "user" : "Users" ]
    dict = [String : String](uniqueKeysWithValues: dict.sorted{ $0.key < $1.key 
    })
Aman Pathak
  • 219
  • 2
  • 6