我正在尝试按离用户最近的距离对 tableView 的结果进行排序。我已经将距离和函数分开来填充距离,以便更好地掌握我的数据操作。我觉得它应该很简单,但我知道我想念它。
距离函数是这样的:
func calculateDistance(userlat: CLLocationDegrees, userLon:CLLocationDegrees, venueLat:CLLocationDegrees, venueLon:CLLocationDegrees) -> Double {
let userLocation:CLLocation = CLLocation(latitude: userlat, longitude: userLon)
let priceLocation:CLLocation = CLLocation(latitude: venueLat, longitude: venueLon)
//let distance = String(format: "%.0f", userLocation.distance(from: priceLocation)/1000)
return userLocation.distance(from: priceLocation)/1000
}
填充数据函数:
func populateData() {
//Pulls TableData for UITableView
DataService.ds.REF_VENUE.observe(.value, with: { (snapshot) in
self.posts = [] // THIS IS THE NEW LINE
if snapshot.exists(){
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
if let snapValue = snap.value as? [String:AnyObject],
let venueLat = snapValue["LATITUDE"] as? Double,
let venueLong = snapValue["LONGITUDE"] as? Double
{
let distance = self.calculateDistance(userlat: self.userLatt, userLon: self.userLonn, venueLat: venueLat, venueLon: venueLong)
if distance <= 2 {
let key = snap.key
let post = Post(postKey: key, postData: snapValue)
self.posts.append(post)
self.posts.sort(by: (posts, distance)) //Where I'm trying to sort
}
}
}
self.getDataForMapAnnotation()
}
self.tableView.reloadData()
}
})
}
我不确定我是否可以对字典数组进行排序,但最终目标是让 tableView 显示离用户最近的地点。如果您有任何建议,请告诉我!
最佳答案
如果将计算的距离添加为 Post 类/结构的属性,则按距离对帖子数组进行排序将非常简单。使用the Swift shorthand syntax for closures ,您的排序函数可能如下所示:
self.posts.sort {
return $0.distance < $1.distance
}
这将按距离升序对帖子数组进行排序。
关于ios - 在 TableView 中按距离排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47081460/