我正在尝试使用多个键值字典创建一个参数请求,并且它创建的很好。但是每次使用随机键-值顺序创建字典时。如何对字典键进行排序或排序。 示例:
[
"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"
]
订单应为:channelid,appdtls,devicedtls,locationdtls,令牌,signcs
输出必须仅在字典中。
答案 0 :(得分:3)
不幸的是,Dictionary数据结构不是为任何排序的存储设计的。但是,您可以对键进行排序并以数组的形式获取它。
let dictionary = [
"A" : [1],
"Z" : [3],
"C" : [2]
]
let keysSorted = Array(dictionary.keys).sorted(<)
然后,您可以遍历已排序的数组并通过键查找字典值。希望对您有帮助!
答案 1 :(得分:0)
您没有添加任何代码,因此可以尝试以下操作:(您可以根据需要更改符号。要以哪种升序或降序排列)
let sortedDict = YourDictionary.sorted(by: {$0.0 > $1.0})
如果您要调用API,则参数的顺序无关紧要。
答案 2 :(得分:0)
您尝试以下代码。
var dict = ["name" : "Test", "user" : "Users" ]
dict = [String : String](uniqueKeysWithValues: dict.sorted{ $0.key < $1.key
})