如何按距坐标和模型的距离对数组进行排序

How to sort array by distance from coordinates and model

我如何在将数组重新构建为模型后按距离对数组进行排序。在我将其过滤回课程格式之前对其进行排序。我做错了什么?

class FeedCourseListViewModel: ObservableObject {

  let locationManager = LocationManager.shared
  let courses: [Course]
  var nearestCourses = [Course]()

  init(courses: [Course]) {
    self.courses = courses
    fetchClosestCourses()
  }

  func fetchClosestCourses() {
    if let location = locationManager.location {
      let clLocationArray = courses.map { CLLocation(latitude: [=10=].location.latitude, longitude: [=10=].location.longitude) }
      let sortedLocations = clLocationArray.sorted(by: { location.distance(from: [=10=]) < location.distance(from: )})
      let prefixedLocations = sortedLocations.prefix(20)
      let nearestLocations = courses.filter { course in
        prefixedLocations.contains { location in
          course.location.latitude == location.coordinate.latitude && course.location.longitude == location.coordinate.longitude
        }
      }
      nearestCourses = nearestLocations
    }
  }
}

struct Course: Identifiable, Decodable {
  let id: String
  let name: String
  let location: Location
}

struct Location: Decodable {
  let latitude: Double
  let longitude: Double
}

您正在做:
[课程] => [CLLocation] => [已排序 - CLLocation] -> [第 20 个 - 已排序 - CLLocation]
筛选 [Courses](如果它在之前的结果中)。

但是,您应该直接对 Courses 进行排序,并首先获得 20。

let sortedCourses = courses.sorted(by: { aCourse1, aCourse2 in 
    let location1 = CLLocation(latitude: aCourse1.location.latitude, longitude: aCourse1.location.longitude) 
    let location2 = CLLocation(latitude: aCourse2.location.latitude, longitude: aCourse2.location.longitude)
    return location.distance(from: location1) < location.distance(from: location2) })

nearestCourses = Array(sortedCourses.prefix(20))