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

SwiftUI中如何对嵌套对象数组使用.contains进行过滤

筛选包含符合距离范围路线的Location的高效实现

解决方案

你可以利用Swift集合的contains(where:)方法(或Swift 5.7+的any方法),检查Location下的所有Route是否存在符合距离范围的项,同时保持原有filter的简洁结构:

写法1(兼容所有Swift版本)

return locations.places.filter { location in
    location.routes.contains { route in
        (minDistance..<maxDistance).contains(route.distance)
    }
}

写法2(Swift 5.7+ 更简洁)

return locations.places.filter { location in
    location.routes.any { (minDistance..<maxDistance).contains($0.distance) }
}

说明

  • 原代码只检查了routes[0],会遗漏其他符合条件的Route;而contains(where:)/any会遍历Location的所有Route,只要找到任意一条满足距离范围的Route,就会判定该Location符合筛选条件,不会遗漏结果。
  • 这两种写法都保持了你想要的locations.places.filter { location in }结构,代码简洁且高效——因为一旦找到符合条件的Route就会停止遍历,不需要检查全部5个Route,性能上完全够用。
  • 你尝试的location.routes[*].distance不是Swift的合法语法,所以会报错,改用集合的判断方法就能解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:02:36