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
CoreDataManager.swift
in the Project navigator (inside theCore Data
folder in theMisc
folder) and add the following method before theaddReview(_:)
method:func fetchRestaurantRating(by identifier:Int) -> Double { let reviews = fetchReviews(by: identifier) let sum = reviews.reduce(0, {$0 + ($1.rating ?? 0)}) return sum / Double(reviews.count) }
In this method, all reviews for a particular restaurant are fetched from the persistent store and assigned to
reviews
. Thereduce()
method takes a closure, which is used to add all the review ratings...