In Swift I understand NSNumbers are containers that contain scalar numbers.
InFirebase you can send NSNumbers to the database but not Ints.
I'm using Firebase Transactions for a number of likes/upvotes and I need to increase the number of times a user presses the upvote button.
Here's my code to send the data to Firebase:
likesRef?.runTransactionBlock({
(currentData: MutableData) -> TransactionResult in
var value = currentData.value as? NSNumber
if value == nil{
value = 0
}
let one: NSNumber = 1
currentData.value = value! += one //error is here
return TransactionResult.success(withValue: currentData)
I keep getting error:
Binary operator '+=' cannot be applied to two 'NSNumber' operands
The problem is I'm passing a Firebase MutableData
type to the success(withValue: )
method and not the NSNumber value itself. I can't use NSNumber.intValue
because Firebase doesn't accept Ints.
How can I increment two NSNumbers together to send to to Firebase as part of a MutableData object?
Try this:
let newValue: Int
if let existingValue = (currentData.value as? NSNumber)?.intValue {
newValue = existingValue + 1
} else {
newValue = 1
}
currentData.value = NSNumber(value: newValue)