Calculating a restaurant's overall rating
The Restaurant Detail screen's overall rating label displays 0.0, and the ratings view displays 3.5 stars, regardless of the actual rating. To add an overall rating, you need to get the ratings from all the reviews and average them. Let's add a new method to CoreDataManager
to do this. Follow these steps:
- Click the
CoreDataManager
file inside the Project navigator (inside theCore Data
folder in theMisc
folder). Add the following method before theaddReview(_:)
method:func fetchRestaurantRating(by identifier: Int) -> Double { let reviewItems = fetchReviews(by: identifier) let sum = reviewItems.reduce(0, {$0 + ($1.rating ?? 0)}) return sum / Double(reviewItems.count) }
In this method, all reviews for a particular restaurant are fetched from the persistent store and assigned to reviews
. The reduce()
method takes a closure, which is used...