title: Swift functional way to get single item from a subarray
body: <p>I have the following function (example), which I would like to write in a functional way:</p>
  
  <pre><code>func passengerForId(_ id: Int) -&gt; Passenger?
  {
      for car in cars
      {
          for passenger in car.passengers
          {
              if passenger.id == id
              {
                  return passenger
              }
          }
      }
      return nil
  }
  </code></pre>
  
  <p>What would be the best way?</p>
  
  <p>I've tried the following:</p>
  
  <pre><code>func passengerForId(_ id: Int) -&gt; Passenger?
  {
      return cars.first(where: { $0.passengers.contains(where: { $0.id == id } ) })
  }
  </code></pre>
  
  <p>However, that obviously returns the car containing the requested passenger, and not the passenger itself.</p>
  
  <p>Another option would something like:</p>
  
  <pre><code>func passengerForId(_ id: Int) -&gt; Passenger?
  {
      let passengers = cars.flatMap { car in car.passengers }
      return passengers.first(where: { $0.id == id })
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>func passengerForId(_ id: Int) -&gt; Passenger?
  {
      return cars.flatMap { car in car.passsengers.filter { $0.id == id }}.first
  }
  </code></pre>
  
  <p>However, that seems less efficient than the original, as it will loop over  all the areas.</p>
  
  <p>Is there a better way to do this?</p>