Yelp review values

Hi,

I’m working through the Swift networking tutorials at the moment and have noticed that the values for Review don’t appear to be 0, 0.5, 1.0, 1.5 etc. I’m getting values like 3.8, 4.2, 4.6 etc, which don’t match the names of the image assets.

So, I wrote a helper that takes an arbitrary value for Review and adjusts it up or down to the nearest 0.5. Here’s the code…

import Foundation

struct RatingHelper {
    
    // This function takes a rating between 0.0 and 5.0 (for example 3.8) and converts it to the nearest value from the set
    //
    //  0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50
    //
    //  This requires the regular_x.y image assets to be renamed to regular_xy etc.
    //
    static func nearestRating(rating: Double) -> String {
        var fives: Int = Int(10 * rating) / 5
        let units: Int = Int(10 * rating) % 5
        
        if (units >= 2) { fives += 1}
        
        return String((fives * 5))
    }
}

I’m sure it can be made more concise.

1 Like

Cool! Thanks for sharing. I used a different approach. I basically renamed the image files to a scale of 2 to 10. So 2 stars (regular_2) was renamed to 4 (regular_4), 3.5 stars (regular_3.5) was renamed to 7 (regular_7), etc. Then I doubled the restaurant rating value and did a quick round of the value and turned it from a Double into an Int.

So if the rating was 3.7, I would double it, and it would be 7.4. After a Round() it would be 7.0. When converting to an Int, it would be 7, which aligned nicely with the new image names, as the 3.5 star image was now renamed to regular_7.

let ratingImageName = business?.rating != nil
    ? "regular_\(Int(round((business?.rating ?? 0) * 2)))"
    : "regular_0"
                    
Image(ratingImageName)