user5812721 user5812721 - 5 months ago 142
Swift Question

Easiest way to increment a data point in Firebase?

I'm having trouble incrementing a piece of data in Firebase.

Firebase {
clickedCounter: 0
}


This is my code:

@IBAction func plus(sender: UIButton) {
FIRDatabase.database().reference().child("clickedCounter").observeEventType(.Value) { (snap: FIRDataSnapshot) in
let value = FIRDatabase.database().reference().child("clickedCounter") as? NSNumber
let increment = ((value?.intValue)! + ((1 as? NSNumber)?.intValue)!) as? NSNumber
FIRDatabase.database().reference().child("clickedCounter").setValue()
self.clickLabel.text = snap.value?.description as String!
}
}


I also tried:

@IBAction func plus(sender: UIButton) {
FIRDatabase.database().reference().child("clickedCounter").observeEventType(.Value) { (snap: FIRDataSnapshot) in
FIRDatabase.database().reference().child("clickedCounter").setValue((snap.value?.description)! + 1)
self.clickedLabel.text = snap.value?.description as! String!
}
}


For my first my warnings are:

Cast from Int32 to NSNumber always fails


Conditional cast from NSNumber to NSNumber always succeeds


Cast from FIRDatabaseReference to NSNumber always fails


After I ran it, I got the error on
let increment....
:
Thread 1: EXC_BAD_INSTRUCTION


For my second the error is:

Binary operator + cannot be applied to operands of the type String and Int



  1. I'm confused as to how my
    snap.value?.description
    is a String when I thought I defined it in Firebase as an Int.

  2. Why do I get a warning when something always succeeds?

  3. Is there a better way to do this?



Thanks!

Jay Jay
Answer

Why not (v2.x Firebase code but you get the idea)

counterRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
     let valString = snapshot.value
     var value = valString.intValue
     value = value + 1
     counterRef.setValue("\(value)")         
})

If this is going to be updated frequently by multiple users, leverage a transaction block as well.