Home > Software engineering >  Retrieve child entry from Firebase Realtime Database without []. - Swift 5
Retrieve child entry from Firebase Realtime Database without []. - Swift 5

Time:02-10

I'm a little stuck with something small but that is giving me some headaches! I have a Realtime Database and I am able to retrieve the information I need from it. My only problem is that instead of printing for example (ex.: 200) is printing (ex.: [200])!

This is my code:

func readData() {

  FirebaseDatabase.Database.database().reference().child("Available_Funds").observeSingleEvent(of: .value, with: { snapshot in
            guard let value = snapshot.value as? [String: Any] else {
                return
            }
            let amountWallet = value.values
            print(amountWallet)
            self.currentBalanceLabel.text = "$"   "\(amountWallet)"
            print("\(value)")
        })
    }

Right now what I get printed with this code is $[200] for example, instead of just $200, which is what I intend to get.

Tried looking online, but no luck with this! Does someone know how to remove these square brackets from printing?

CodePudding user response:

values is an Array -- thus the []. When you say value.values, you're asking for all of the values of the key/value pairs in snapshot.value.

If you intend to get a single value from it, you would use amountWallet[0] to get the first element. Keep in mind that this will crash if amountWallet has 0 elements (arrays are zero indexed).

amountWallet.first will give you an Optional that will be safe to use, but you would need to unwrap it for printing:

let amountWallet = value.values
if let singleAmount = amountWallet.first {
  print(singleAmount)
  self.currentBalanceLabel.text = "$"   "\(singleAmount)"
}
            

CodePudding user response:

You're calling it back as an array of strings [String: Any]

You can either change this (remove []) or access the first element in the array: amountWallet[0].

  • Related