func incrementStars()

in database/DatabaseExampleSwift/PostTableViewCell.swift [49:81]


  func incrementStars(forRef ref: DatabaseReference) {
    // [START post_stars_transaction]
    ref.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
      if var post = currentData.value as? [String: AnyObject],
        let uid = Auth.auth().currentUser?.uid {
        var stars: [String: Bool]
        stars = post["stars"] as? [String: Bool] ?? [:]
        var starCount = post["starCount"] as? Int ?? 0
        if let _ = stars[uid] {
          // Unstar the post and remove self from stars
          starCount -= 1
          stars.removeValue(forKey: uid)
        } else {
          // Star the post and add self to stars
          starCount += 1
          stars[uid] = true
        }
        post["starCount"] = starCount as AnyObject?
        post["stars"] = stars as AnyObject?

        // Set value and report transaction success
        currentData.value = post

        return TransactionResult.success(withValue: currentData)
      }
      return TransactionResult.success(withValue: currentData)
    }) { error, committed, snapshot in
      if let error = error {
        print(error.localizedDescription)
      }
    }
    // [END post_stars_transaction]
  }