Why can't I read the value outside an observable

Viewed 22

I am new to swift and trying to teach myself how to build and iOS app. I hooked up the backend to a Firebase Realtime Database and I am able to successfully read and write to the DB but I cannot access the values outside of an observable.

import UIKit
import Firebase

class ViewController: UIViewController {
    
    var ref:DatabaseReference!
    var test12:String!
    
    override func viewDidLoad() {
        
        self.ref = Database.database().reference()
        
        self.ref.child("Title").child("Name").observe(.value) { snapshot in
            self.test12 = snapshot.value! as? String
            print(self.test12!)
        }
        print(self.test12!)
        super.viewDidLoad()
    }
}

The first print(self.test12!) prints out correctly so I know I am getting the correct information from there DB, but the second one errors out. How can I use the information I get back from the DB throughout my program?

1 Answers

The reason only 1 of your 2 print statements is printing the object is because it's within the asynchronous handler of the observe method. The second print statement is called synchronously after observe is first called, so it would use self.test12 before it's been populated.

If you want anymore info on what's going on here - you can look into multi-threading and GrandCentralDispatch.

Related