首页 > 解决方案 > 如何对字典类型中的特定值求和

问题描述

我正在创建评论功能。我想显示评论星。我目前在 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求和。

如何对字典中的值求和?

标签: iosswiftfirebasedictionarygoogle-cloud-firestore

解决方案


你可以试试

let res = reviews.map { $0.rate }.reduce(0,+)

推荐阅读