0

I am developing an app with Xcode and the Swift programming language. Keep in mind my app works closely with Firebase. I created a function to retrieve a parameter from Firebase based on a key.

// My global variables. 'ref' is my firebase database and 'returnValue' is the value I am trying to write to withing the closure.
var ref = Database.database().reference(withPath: "accounts")
var returnValue: String = ""


func getParam(key: String) -> String {
    let index = defs.integer(forKey: "index")

    self.returnValue = "Failed retrieving parameter in getParam() function"

    self.ref.child("data").observeSingleEvent(of: .value) { (snapshot) in

        let data = snapshot.value! as! NSArray
        let dictionary = data[index] as! NSDictionary
        self.returnValue = String(describing: dictionary[key])
        print("returnValue:", self.returnValue) //First line in console
        return
    }
    return self.returnValue
}
override func viewDidLoad() {
    super.viewDidLoad()
    print(getParam("status")) //Second line in console
}

Whenever I call this function I see this in the console:

returnValue: Optional(0) //take in mind this is the output I am looking for in the second line

Failed retrieving parameter in getParam() function

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 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). Your call is asynchronous so your `print` statement is executed before the data has been downloaded from firebase (and there is very little point in returning an instance property anyway) – Joakim Danielson Mar 19 '20 at 15:38

1 Answers1

0

When you call observeSingleElement, it is run synchronously, meaning the current thread sends it off and ignores whatever it does.

return self.returnValue

and has nothing to do with the closure in observeSingleElement. You could pass a closure to

func getParam(key: String, completion: (String) -> Void) {
    let data = snapshot.value! as! NSArray
    let dictionary = data[index] as! NSDictionary
    let returnValue = String(describing: dictionary[key]) ?? "Failed retrieving parameter in getParam() function"
    completion(returnValue)
 }
HalR
  • 11,411
  • 5
  • 48
  • 80