2017-11-05 7 views
0

Swiftでは、NSNumbersはスカラー番号を含むコンテナであることを理解しています。Swift 3.2 iOS - Firebase MutableDataオブジェクトのNSNumberを増やす方法は?

InFirebaseあなたはデータベースにNSNumbersを送信できますが、Intsは送信できません。

私はFirebase Transactionsを多数のお気に入り/アップボードに使用しています。ユーザーがupvoteボタンを押した回数を増やす必要があります。

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

私はエラーを取得しておいてください。

Binary operator '+=' cannot be applied to two 'NSNumber' operands

enter image description here

問題は、私はFirebase MutableDataタイプを渡しているありますsuccess(withValue:)メソッドであり、NSNumber値自体ではありません。 FirebaseはIntsを受け入れないので、私はNSNumber.intValueを使用できません。

MutableDataオブジェクトの一部として2つのNSNumbersをまとめてFirebaseに送信するにはどうすればよいですか?

答えて

1

はこれを試してみてください:

let newValue: Int 

if let existingValue = (currentData.value as? NSNumber)?.intValue { 
    newValue = existingValue + 1 
} else { 
    newValue = 1 
} 

currentData.value = NSNumber(value: newValue) 
+0

おかげで、私は時間のカップルでまたはので、それを試してみて、あなたに戻って、私が開いて中括弧**(CURRENTDATA前に、2行目にエラーを取得保管 –

+0

を取得します。 ?NSNumberとしての値)?value **。エラーは** "値"の曖昧な使用**です。私は**(currentData.value as NSNumber)?intValue **を代わりに使用していました。私はSwift 3.2を使用していますが、**。intValue **の** value **を切り替えることでそれを更新する必要があります。それ以外のあなたの答えは素晴らしい作品です!ありがとう:) –

0

あなたはUINTの代わりのIntを使用することができます。これは、私の作品:

.runTransactionBlock { (currentData) -> TransactionResult in 

     if var value = currentData.value as? UInt { 
      value += 1 
      currentData.value = value 
     } else { 
      currentData.value = UInt(1) 
     } 

     return TransactionResult.success(withValue: currentData) 
    } 
} 
関連する問題