Filter using .contains for a nested array

I have an app that displays a large number of physically marked walking routes in The Netherlands. Loads of fun. For my next release I'm planning to add filters to the map, to make it easier to find the best route.

I have build a solution for that, but I'm sure there's a more efficient or clean way to do this. Thus I turn to you, the community, for a sanity check.

My setup data structure wise (unchangeable) - simplified to relevant-only for readability:

struct Location: Codable, Identifiable, Hashable, Equatable {
    let id: Int
    let longitude, latitude: Double
    let routes: [Route]
}

struct Route: Codable, Identifiable {
    let id : Int
    let marking: String
    let distance: Double
}

I have an array of Location objects, which in turn include an array of Route objects (max 5).

Each route has a distance (length of the walk) attribute. I want to filter for a specific distance. Routes are ordered by length inside a Location. So the shortest walk at a specific location is locations.place[xyz].route[0]

I have a filter button setup that outputs a minDistance and maxDistance : Double that I feed into the filter fund.

My current filter function solution checks index 0:

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

This returns an array of locations where route[0] (the shortest walk at the location) matches the user's preferred walk length.

This means that I miss a fair amount of positive results. I feel like something like this should be possible, to check all routes at a location:

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

Unfortunately this doesn't work. Neither does [0...5] or similar thoughts.

As I'm quite new at developing, and I only have short bursts of time to work on this app, I feel like I might be missing something very obvious here.

Is there a way to change the .contains(location.routes[something-goes-here].distance) check to test all routes and not just index 0?

Accepted Reply

Bit old topic, but might as well add the ultimately implemented solution if anyone else needs something similar.

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

Replies

Bit old topic, but might as well add the ultimately implemented solution if anyone else needs something similar.

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