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.