Rya*_*ton 2 swift alamofire swifty-json
我无法简洁地从api中提取数据,将用户当前位置添加到对象中,然后根据计算的距离对数据进行排序.
stackoverflow问题并没有完全解决我面临的问题.请参阅:如何对从Swift中的JSON服务器文件中读取的帖子进行排序.
我目前正在从Alamofire加载api数据并使用UITableViewController渲染该数据.
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.title = q.capitalizedString
Alamofire.request(.GET, "http://www.thesite.com/api/v1/things", parameters: ["q" : q])
.responseJSON { response in
let JSONObject = JSON(response.result.value!)
self.results = JSONObject["things"]
for (key, _) in self.results {
let intKey: Int = Int(key)!
var thisItem: JSON = self.results[intKey]
let geoLat = thisItem["place"][0]["location"]["geo"][1].double ?? 37.763299
let geoLong = thisItem["place"][0]["location"]["geo"][0].double ?? -122.419356
let destination = CLLocation(latitude: geoLat, longitude: geoLong)
let setLocation = CLLocation(latitude: self.currentLocation.latitude, longitude: self.currentLocation.longitude)
let distanceBetween: CLLocationDistance = destination.distanceFromLocation(setLocation)
thisItem["distance"].double = distanceBetween
self.results[intKey] = thisItem
}
self.tableView.reloadData()
}
}
Run Code Online (Sandbox Code Playgroud)
我从api获取数据并成功添加用户位置和地点目的地之间的距离.
但是,现在我需要从最低到最高距离对JSON对象(SwiftyJSON)进行排序.这就是我被困住的地方.
tableView(作为JSON对象)重新加载时的数据结构基本上是:
results = [
{"title": "Chai", "distance": "1245.678575"},
{"title": "Espresso", "distance": "765845.678575"},
{"title": "Drip Coffee", "distance": "23445.678575"}
...
]
Run Code Online (Sandbox Code Playgroud)
我怎么能够:1)将对象转换为NSArray并排序; 或2)只是排序对象?什么时候做距离添加和排序的最佳位置 - 我应该在转换为JSON对象之前做到这一点.
任何帮助表示赞赏!谢谢!
aya*_*aio 10
如果results是SwiftyJSON对象,则可以使用提取其数组.arrayValue.
let resultsArray = results.arrayValue
Run Code Online (Sandbox Code Playgroud)
然后,一旦你有了一个正常的字典数组,你就可以sort像这样对数组进行排序:
let sortedResults = resultsArray.sort { $0["distance"].doubleValue < $1["distance"].doubleValue }
Run Code Online (Sandbox Code Playgroud)
我拿了你的JSON片段:
并在SwiftyJSON的Playground中测试了我的答案:
如果您愿意,还可以直接对SwiftyJSON对象进行排序:
let sortedResults = results.sort { $0.0.1["distance"].doubleValue < $0.1.1["distance"].doubleValue }.map { $0.1 }
Run Code Online (Sandbox Code Playgroud)
但我觉得它作为源代码的可读性较差.
| 归档时间: |
|
| 查看次数: |
5288 次 |
| 最近记录: |