title: In what order does Swift evaluate functions?
body: <p>I have a function that has a function within it in terms of a call to a firebase database. </p>
  
  <p>The internal function sets the value of a variable from the wrapper function, but my output does not register this. When debugging it looks like this happens in reverse order. I'm new to swift and firebase so i'm just trying to get my head round this. </p>
  
  <p>This is my function and output. </p>
  
  <pre><code>func checkIfUsernameExists(inUsername: String) -&gt; String{
      var aString = "false"
      let ref = FIRDatabase.database().reference()
  
      ref.child("-KohvyrIikykRsOP0XCx").observeSingleEvent(of: .value , with: {(snapshot) in
          if snapshot.hasChild(self.username.text!){
              print ("*** username already exists")
              aString = "true"
          }
      })
  
      print ("*** value of aString is: ", aString)
      return aString
  }
  </code></pre>
  
  <p>output is: </p>
  
  <pre><code>*** value of aString is:  false
  *** username already exists
  </code></pre>
  
  <p>Edit: </p>
  
  <p>I phrased my question poorly i think. </p>
  
  <p>What i meant to ask was how can i get the call back from firebase before processing the information its collected. I've bounced round SO and lots of blogs all pointing to Async, GCD and Completion handlers. None of which seemed to work or were easy enough for noob to get their head round. </p>
  
  <p>Needless to say i've found my answer here. </p>
  
  <p><a href="https://stackoverflow.com/questions/40135276/firebase-swift-3-completion-handler-bool">Firebase Swift 3 Completion handler Bool</a></p>
  
  <p>This is what i used: </p>
  
  <pre><code>func checkIfUsernameExists(userid: String, completionHandler: @escaping ((_ exist : Bool) -&gt; Void)) {
  
  
          let ref = FIRDatabase.database().reference()
          ref.child("-KohvyrIikykRsOP0XCx").observeSingleEvent(of: .value , with: {(snapshot) in
              if snapshot.hasChild(self.username.text!){
                  self.usernameCheck = "true"
                  completionHandler(true)
                  }
  
               else {
                  self.usernameCheck = "false"
                  completionHandler(true)
                  }
          })
  }
  </code></pre>