How to sort JSON coming from Alamofire and return final JSON object (swiftyJSON)

最后都变了- 提交于 2019-12-04 17:10:47

If results is a SwiftyJSON object, you can extract its array with .arrayValue.

let resultsArray = results.arrayValue

Then once you have a normal array of dictionaries, you can then sort the array with sort like this:

let sortedResults = resultsArray.sort { $0["distance"].doubleValue < $1["distance"].doubleValue }

I took your JSON snippet:

And tested my answer in a Playground with SwiftyJSON:


If you wanted to, you could also sort the SwiftyJSON object directly:

let sortedResults = results.sort { $0.0.1["distance"].doubleValue < $0.1.1["distance"].doubleValue }.map { $0.1 }

But I find it less readable as source code.

Swift 3 & Swift 4

let sortedResults = finalJsonArray.sorted { $0["count"].doubleValue < $1["count"].doubleValue }

Swift 3 + Swift 4 Shortest solution I've found is below:

< is sorting ascending,
> is sorting descending

It is especially very efficient for sorting (String,JSON) format (when you work with SwiftyJSON)

let sortedResults = json.sorted(by: < )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!