-1

I make a call to Firebase database to update the variable cars. My database has children. When I print cars in the call's loop I get all my car's name but out of it it an empty string array. For example, when I print cars from viewDidLoad out of the observe method, it is [ ].

let ref = Database.database().reference()
var cars: [String] =  []

override func viewDidLoad() {
    super.viewDidLoad()

    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        let value = snapshot.value as? NSDictionary
        for child in value! {
            self.cars.append(child.key as! String)
        }
      }) { (error) in
        print(error.localizedDescription)
    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Jet
  • 1
  • 2
  • 2
    Does this answer your question? [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function). Most likely you are trying to access your variable before the data has been returned from the asynchronous call. – Joakim Danielson May 16 '20 at 12:44

1 Answers1

1

When I print cars in the call's loop

The snippet you posted is not a "call's loop" but a callback block. That means that the code you put in there is being executed once the request finishes. So when you print outside of the callback block the array will mostly be empty, because the data is simply not there yet.

RedX
  • 461
  • 1
  • 4
  • 14