我正在尝试按最接近用户的距离对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
}
PopulateData函数:
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显示最接近用户的场所。如果您有任何建议,请告诉我们!
答案 0 :(得分:1)
如果您将计算的距离添加为Post类/结构的属性,则按距离对posts数组进行排序将非常简单。使用the Swift shorthand syntax for closures,您的排序函数可能如下所示:
self.posts.sort {
return $0.distance < $1.distance
}
这将按照距离按升序对posts数组进行排序。