You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按与当前坐标的距离排序数组并正确映射回Course模型

问题原因

  • 你对clLocationArray做了排序得到sortedLocations,但后续你是调用原始courses数组的filter方法筛选符合条件的课程。filter方法会严格按照原数组的元素顺序返回匹配结果,完全不会继承你之前给位置数组做的排序规则,所以排序结果自然丢失了。
  • 额外潜在问题:你用经纬度完全相等做匹配,浮点型数值直接用==比较很容易出现精度误差,就算是同一个位置计算出来的经纬度也可能因为微小的精度差匹配失败。

修复方案

直接对原courses数组按距离排序即可,不需要拆分位置和课程两个数组单独处理:

func fetchClosestCourses() {
    if let location = locationManager.location {
        nearestCourses = courses
            .sorted { course1, course2 in
                let loc1 = CLLocation(latitude: course1.location.latitude, longitude: course1.location.longitude)
                let loc2 = CLLocation(latitude: course2.location.latitude, longitude: course2.location.longitude)
                return location.distance(from: loc1) < location.distance(from: loc2)
            }
            .prefix(20)
            .map { $0 }
    }
}

如果想要优化性能避免重复创建CLLocation,可以先把课程和对应的距离绑定再排序:

func fetchClosestCourses() {
    if let location = locationManager.location {
        // 先把课程和对应距离绑定成元组
        let courseWithDistance = courses.map { course in
            (course: course, distance: location.distance(from: CLLocation(latitude: course.location.latitude, longitude: course.location.longitude)))
        }
        // 按距离排序后取前20,再提取课程数组
        nearestCourses = courseWithDistance
            .sorted { $0.distance < $1.distance }
            .prefix(20)
            .map { $0.course }
    }
}

内容的提问来源于stack exchange,提问作者tonileipo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:36:02