【问题标题】:How to sort array by distance from coordinates and model如何按距坐标和模型的距离对数组进行排序
【发布时间】:2021-11-04 05:22:24
【问题描述】:

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

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: $0.location.latitude, longitude: $0.location.longitude) }
      let sortedLocations = clLocationArray.sorted(by: { location.distance(from: $0) < location.distance(from: $1)})
      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
}

【问题讨论】:

  • nearestCourses = 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) &lt; location.distance(from: location2) }).prefix(20) ?不要映射到排序,稍后再重新过滤,直接在顶层排序。

标签: arrays swift core-location


【解决方案1】:

你正在做:
[课程] => [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))

【讨论】:

  • 它在尝试将“nearestCourses”转换为 [Course] 时说:无法将类型“Array.SubSequence”(又名“ArraySlice”)的值分配给类型“[Course]”
  • 现在应该修复
  • 现在工作。谢谢!
  • 为什么不简单地location.distance(from: $0.location) &lt; location.distance(from: $1.location)
  • 因为$0.locationLocation,而不是CLLocation。我可以将计算属性asCLLocation 添加到Location,然后可能将cllocation 添加到Course,但是当主要逻辑仍在直接对courses 执行操作时,这可能会更进一步。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
相关资源
最近更新 更多