How to sum a specific value in a dictionary type

Refresh

January 2019

Views

53 time

1

I'm creating reviews function. I want to display review stars. I currently have the following data in the Firestore documentation

[
 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")
        )
 ]

We then added this data to the reviews array using queries.

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)
            }
        }
    }
}

From here, I'd like to extract rate from the array ​​assigned toreview and add Int to sum it.

How can I sum the values in the dictionary?

1 answers

3

You can try

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