Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

swift5 - JSON Response data Ascending values in swift

"buttons": [
 {
 "payload": "3",
 "title": "Check my money transfer status"
 },
 {
 "payload": "1",
 "title": "Need help with money transfer"
 },
 {
 "payload": "2",
 "title": "Have a question on Western Union locations"
 },
 {
 "payload": "4",
 "title": "General questions"
 }
 ]

I am getting the above response but the orders are different. I need to sort the order based on payload ascending order

I want the Final Output to look like this below:

"buttons": [
{
 "payload": "1",
 "title": "1. Need help with money transfer"
},
{
"payload": "2",
"title": "2. Have a question on Western Union locations"
},
{
"payload": "3",
"title": "3. Check my money transfer status"
},
{
"payload": "4",
"title": "4. General questions"
}
]
question from:https://stackoverflow.com/questions/65952627/json-response-data-ascending-values-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First you need to convert the json to dictionary. I hope you've done that. If not, refer this answer for doing that - https://stackoverflow.com/a/33173192/4637057

Once that is completed, you can follow this to get a sorted array. (I just gave the resulting dictionary, some name as "yourDictionary")

if var buttonArray = yourDictionary["buttons"] as? [Dictionary<String,String>] {
    buttonArray = buttonArray.sorted {
        ($0["payload"] ?? "") < ($1["payload"] ?? "")
    }
    print(buttonArray)
}

I suggest you learn about Swift higher order functions to learn more about these kind of techniques. This is a pretty good tutorial for that - https://www.appcoda.com/higher-order-functions-swift/

Check the "Sorted" section in that tutorial to get an idea about sorting in particular.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...