I have a loop that runs slowly. Is there a more efficient way of checking two arrays against each other in swift.
for photo in foodPhotos {
for restaurant in self.restaurants {
if (restaurant.objectId == photo.objectId){
self.detailsForFoodPhotos.append(restaurant) // create array of ordered restaurants
break // break if we find the matching restaurant
}
}
}
Explanation
For each element, the loop finds the objectId in the first array ( foodPhotos) that matches the objectId of an element in the second array (restaurants).
If the objectIds match, save the restaurants element in detailsForFoodPhotos. Continue until all foodPhotos have been checked.
Example:
Array of Photos: foodPhotos:
[ photo1, photo2, photo3 ]
Array of Restaurants restaurants:
[ restaurant1, restaurant2, restaurant3, restaurant4, restaurant3 ]
The loop checks which photo.objectID matches restaurant.objectID. Then creates a new array with the matching restaurants.
Output Array: detailsForFoodPhotos
[ restaurant3, restaurant1, restaurant2 ]
// photo1.objectID == restaurant3.objectID
// photo2.objectID == restaurant1.objectID
// photo3.objectID == restaurant2.objectID