title: check if key exists firebase 4 and swift 4?
body: <p>How do I check if a key exists in Firebase? I have seen this link <a href="https://stackoverflow.com/questions/37405149/how-do-i-check-if-a-firebase-database-value-exists">here</a>, but it's for Firebase 3, and it doesn't work for my situation. So for my case, I want to check to see if a username exists, and if it does, then don't register a user, but if it doesn't then register. I have something along the lines of this:</p>
  
  <pre><code>        let usersDB = Database.database().reference().child("Users")
          var taken = false
  
          usersDB.observeSingleEvent(of: .value, with: { (snapshot) in
              if snapshot.hasChild(username) {
                  taken = true
                  self.errorLabel.text = "Username already taken."
              }
          })
  
          if !taken {
              // Email registration
              Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
                  if error != nil {
                      print(error!.localizedDescription)
                      self.errorLabel.text = error!.localizedDescription
                  } else {
                      // Allows for username log in
                      usersDB.child(username).setValue(["email" : user?.email])
                      self.performSegue(withIdentifier: "goToGroups", sender: self)
                  }
              })
          }
  </code></pre>
  
  <p>The <code>observeSingleEvent</code> is what the previous similar post's solution was, but it only runs after I add a child on this line <code>usersDB.child(username).setValue(["email" : user?.email])</code>, <strong>it never runs before.</strong> Is there any other way to do this? </p>