Home > OS >  How do I remove first three elements in Array in Swift?
How do I remove first three elements in Array in Swift?

Time:10-19

I have this button I press that gives me access to 3 reviews. The problem Im having is that it keeps adding on to the other 3 reviews that are stored. How would I remove the first 3 reviews before adding the next 3 reviews?

self.fetchReviews(id: venue.id ?? "no number", locale: "en_US") { (response, error) in
guard let validResponse = response else {return}

for review in validResponse {

//This is were I append the reviews to my Array
self.resturantReviews.append(review.text!)
tableView.reloadData()

}

CodePudding user response:

Removing the first 3 reviews before adding the next 3 reviews is actually replacing the items.

An easy way is mapping the array, compactMap unwraps the optional safely.

self.resturantReviews = validResponse.compactMap(\.text)
tableView.reloadData()

Side note: Calling tableView.reloadData() inside the loop is very bad practice.

  • Related