You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift评分系统优化:寻求更简洁的遍历赋值实现方案

Swift 评分系统:更简洁的遍历计算方案

嘿,这个需求我太熟悉了!你完全不用写一堆冗长的if/else来把评分分到不同数组里——不管是直接计算最终评分,还是需要先统计各星级数量,都有更优雅的实现方式。

方案一:直接计算加权平均分(最简洁)

如果你的核心需求只是得到最终四舍五入的评分结果,完全不需要拆分到不同数组,直接通过遍历累加加权总分即可:

// 示例:用户的所有评分集合
let userRatings: [Int] = [5, 4, 5, 3, 2, 5, 4]

// 计算加权总分(所有评分的总和),两种写法任选
let totalWeightedScore = userRatings.reduce(0) { accumulated, rating in
    accumulated + rating
}
// 或者更简洁的尾随闭包写法:
// let totalWeightedScore = userRatings.reduce(0, +)

// 计算总评分次数,避免除以0的异常情况
let totalRatingCount = userRatings.count

// 计算平均分并四舍五入到整数
let finalRoundedRating = totalRatingCount > 0 
    ? Int((Double(totalWeightedScore) / Double(totalRatingCount)).rounded()) 
    : 0 // 无评分时返回0,可根据业务需求调整

这个方法用reduce一步完成总分累加,省去了所有条件判断,代码清爽又高效。

方案二:统计各星级数量(兼顾后续扩展)

如果后续需要展示各星级的占比数据(比如五星用户占比多少),可以用字典来自动统计各星级的数量,同样不用if/else:

let userRatings: [Int] = [5, 4, 5, 3, 2, 5, 4]

// 用字典统计每个星级的出现次数,default值避免key不存在的问题
var starCountMap = [Int: Int]()
for rating in userRatings {
    starCountMap[rating, default: 0] += 1
}

// 基于统计结果计算加权总分
let totalWeightedScore = starCountMap.reduce(0) { accumulated, entry in
    accumulated + (entry.key * entry.value)
}
let totalRatingCount = userRatings.count

let finalRoundedRating = totalRatingCount > 0 
    ? Int((Double(totalWeightedScore) / Double(totalRatingCount)).rounded()) 
    : 0

这里利用Swift字典的default下标,自动处理不同星级的计数,再也不用写if rating == 5 { fiveStars.append(rating) } else if ...这种重复代码了。

两种方案最终都能得到你需要的单个四舍五入评分结果,而且代码简洁性和可维护性都比原来的方法好很多~

内容的提问来源于stack exchange,提问作者user7684436

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:13:36