i have loop runs slowly. there more efficient way of checking 2 arrays against each other in swift.
for photo in foodphotos { restaurant in self.restaurants { if (restaurant.objectid == photo.objectid){ self.detailsforfoodphotos.append(restaurant) // create array of ordered restaurants break // break if find matching restaurant } } } explanation
for each element, loop finds objectid in first array ( foodphotos) matches objectid of element in second array (restaurants).
if objectids match, save restaurants element in detailsforfoodphotos. continue until foodphotos have been checked.
example:
array of photos: foodphotos:
[ photo1, photo2, photo3 ] array of restaurants restaurants:
[ restaurant1, restaurant2, restaurant3, restaurant4, restaurant3 ] the loop checks photo.objectid matches restaurant.objectid. creates new array matching restaurants.
output array: detailsforfoodphotos
[ restaurant3, restaurant1, restaurant2 ] // photo1.objectid == restaurant3.objectid // photo2.objectid == restaurant1.objectid // photo3.objectid == restaurant2.objectid
i still think other answer way go. however, haven't accepted it, , you've provided actual data input , desired output, here's solution produces it:
struct photo { let objectid : int } struct restaurant { let objectid : int } let foodphotos = [photo(objectid:1), photo(objectid:2), photo(objectid:3)] let restaurants = [restaurant(objectid:3), restaurant(objectid:1), restaurant(objectid:2)] var d = [int:int]() (ix,r) in restaurants.enumerate() { d[r.objectid] = ix } var detailsforfoodphotos = [restaurant]() p in foodphotos { if let ix = d[p.objectid] { detailsforfoodphotos.append(restaurants[ix]) } } // i'll prove worked print(foodphotos) // [photo(objectid: 1), photo(objectid: 2), photo(objectid: 3)] print(restaurants) // [restaurant(objectid: 3), restaurant(objectid: 1), restaurant(objectid: 2)] print(detailsforfoodphotos) // [restaurant(objectid: 1), restaurant(objectid: 2), restaurant(objectid: 3)] that requires 2 simple loops; both fast. key solution generation of intermediate lookup table (dictionary), d, hashes on objectid index second array.
Comments
Post a Comment