ios - 如何对字典类型中的特定值求和
问题描述
我正在创建评论功能。我想显示评论星。我目前在 Firestore 文档中有以下数据
[
DADA.Review(
uid: Optional("RAMIqHAVeoU4TKkm3FDw7XUwgym2"),
reviewer: Optional("o93WI2UySobPj3fdtMOQvZ4cBng1"),
rate: Optional(4),
description: Optional("I\'m so happy")
),
DADA.Review(
uid: Optional("RAMIqHAVeoU4TKkm3FDw7XUwgym2"),
reviewer: Optional("o93WI2UySobPj3fdtMOQvZ4cBng1"),
rate: Optional(3),
description: Optional("Great")
),
DADA.Review(
uid: Optional("RAMIqHAVeoU4TKkm3FDw7XUwgym2"),
reviewer: Optional("o93WI2UySobPj3fdtMOQvZ4cBng1"),
rate: Optional(3),
description: Optional("NIce seller")),
DADA.Review(
uid: Optional("RAMIqHAVeoU4TKkm3FDw7XUwgym2"),
reviewer: Optional("o93WI2UySobPj3fdtMOQvZ4cBng1"),
rate: Optional(1), description: Optional("Greate seller")
)
]
然后我们使用查询将此数据添加到reviews
数组中。
func fetchReview(){
let userRef = Firestore.firestore().collection("reviews").whereField("uid", isEqualTo: uid!)
userRef.getDocuments() {(querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
}else {
for document in querySnapshot!.documents {
let data = document.data()
let uid = data["uid"] as? String ?? ""
let reviewer = data["reviewer"] as? String ?? ""
let rate = data["rate"] as? Int ?? 0
let description = data["description"] as? String ?? ""
let newReviews = Review(uid: uid, reviewer: reviewer, rate: rate, description: description)
self.reviews.append(newReviews)
}
}
}
}
从这里,我想rate
从分配给的数组中提取review
并相加Int
求和。
如何对字典中的值求和?
解决方案
你可以试试
let res = reviews.map { $0.rate }.reduce(0,+)
推荐阅读
- jenkins - 在 Jenkins 上找不到 TFS 插件
- javascript - 在 Angular 应用程序的新选项卡中打开链接时,ngx-cookie 被删除
- xml - XSD 全局定义多个元素时需要某个 XML 根元素?
- powershell - 使用 Powershell 检查文件是否存在
- android - 如何阻止我的应用内容来自具有“SYSTEM_ALERT_WINDOW”权限的应用
- angular - 仅在 ubuntu 中找不到模块“@module/kinetic-erp-tester-e2e”/tsconfig 路径
- flutter - 在flutter_driver测试中,我们如何自动化我们上传图片或视频的部分?
- c# - 找不到类型或命名空间名称“GlobalFilterCollection”(您是否缺少 using 指令或程序集引用?)
- elasticsearch - 如何在弹性搜索中表示索引映射中的必填字段
- cuda - 为什么不允许 cudaLaunchCooperativeKernel() 返回?