What is the best way to monitor, calculate and display users' ratings? In my case, I want to create a star-based system that will allow users to rate a real-world landmark. Never having done this, and not finding a tutorial to explain how, I figured each rating would be entered into CloudKit / Core Data. Then, for each landmark, a fetch request could be made. The average would then be calculated.
Here's the relevant code that I have been trying. Note that I am passing in the name of the specific landmark as a string (which is used as in a predicate of the fetch method):
var landmark: Landmark
...
let fetchRequest = Rating.fetchRequestForLandmark(landmark: landmark.name)
var ratings: FetchedResults<Rating> {
fetchRequest.wrappedValue
}
var sum: Int32 {
ratings.map { $0.rating }.reduce(0, +)
}
var stars : Int32 {
if (ratings.count > 0) {
return sum / Int32(ratings.count)
} else {
return 0
}
}
The warning I get is:
Cannot use instance member ‘landmark’ within property initializer; property initializers run before ‘self’ is available
I've tried to initalize the landmark object before accessing it’s name property, but I that didn't work either.
Then, on a suggestion I received over at Stack Overflow, I tried wrapping the fetch in a calculated property like this:
var caluculation : (sum: Int, stars: Int) {
let fetchRequest = Rating.fetchRequestForLandmark(landmark: landmark.name)
var ratings: FetchedResults<Rating> {
fetchRequest.wrappedValue
}
if (ratings.count > 0) {
print("Ratings count is greater than zero")
let sum = ratings.map { $0.rating }.reduce(0, +)
let stars = sum / Int32(ratings.count)
return (sum: Int(sum), stars: Int(stars))
} else {
print("ratings count not greater than zero")
return (sum: 0 , stars: 0)
}
}
The warning goes away, and the build succeeds; however, the print statements tell me that the fetch is returning up empty (ratings.count is always 0), even when I know there is data there.
If anyone can help me fix this code, or guide me to a good tutorial or suggest a different approach, I will be very, very grateful.
Thanks!