【发布时间】: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) < location.distance(from: location2) }).prefix(20)?不要映射到排序,稍后再重新过滤,直接在顶层排序。
标签: arrays swift core-location