Home > Enterprise >  Add a completion for sorting an Array
Add a completion for sorting an Array

Time:12-22

I have a list of urls and I will scrape the data of the urls, it take a bit of time so I get each data one by one. but not in the correct order, and then, I will append this data to an array, then set this array to another array which populate data in a UICollectionView. But I have to sort the final array as well, in my current approach, it sorts array when the data is on the screen, and you can their changing position

discoveryFeeds.append(scraper)
discoveryCollectionView.feeds = discoveryFeeds.sorted(by: {$0.feed.createdAt > $1.feed.createdAt})

I want to change it something like that, knowing when the sorting is done that I can do the rest of the process after that

discoveryFeeds.append(scraper)
discoveryFeeds = discoveryFeeds.sorted(by: {$0.feed.createdAt > $1.feed.createdAt})

// and when sorting is done - send to collectionView
discoveryCollectionView.feeds = discoveryFeeds

could anyone help me on that. Thanks

CodePudding user response:

Sorting is not asynchronous. The "sorting is done" when we proceed to the next line.

So, in your second example,

discoveryFeeds = discoveryFeeds.sorted(by: {$0.feed.createdAt > $1.feed.createdAt})

// and when sorting is done - send to collectionView
discoveryCollectionView.feeds = discoveryFeeds

...indeed, we do not set discoveryCollectionView.feeds until the the sorting is done.

  • Related