Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我的swift代码出了问题?_Swift_Firebase_Firebase Realtime Database - Fatal编程技术网

为什么我的swift代码出了问题?

为什么我的swift代码出了问题?,swift,firebase,firebase-realtime-database,Swift,Firebase,Firebase Realtime Database,我有下面的代码,它似乎执行不正常 var theauth = 0 ref = Database.database().reference() let usersRef = ref?.child("Users") let queryRef = usersRef?.queryOrdered(byChild: "username").queryEqual(toValue: emailTextField.text!) queryRef?.o

我有下面的代码,它似乎执行不正常

var theauth = 0
        ref = Database.database().reference()
        let usersRef = ref?.child("Users")
        let queryRef = usersRef?.queryOrdered(byChild: "username").queryEqual(toValue: emailTextField.text!)
        queryRef?.observeSingleEvent(of: .value, with: { (snapshot) in
            for snap in snapshot.children {
                let userSnap = snap as! DataSnapshot
                let thechild = userSnap.key
                print(thechild + "Hi")
                if thechild != ""{
                    theauth = 3
                    print(thechild + "1")
                }else if self.password2.text == self.passwordTextField.text{
                    theauth = 1
                }else{
                    theauth = 2}
            }
        })

        print(theauth)
输出按与预期相反的顺序打印:

0 //theauth value
-Lf9xUh53VeL4OLlwqQoHi //thechild value + Hi
-Lf9xUh53VeL4OLlwqQo1  //thechild value + 1

想法???

查询是异步的,运行时间比最后的print语句要长。在设置变量时,请考虑添加打印语句,或者在查询完成时调用一个方法来执行该打印语句。
var theauth = 0
ref = Database.database().reference()
let usersRef = ref ? .child("Users")
let queryRef = usersRef ? .queryOrdered(byChild: "username").queryEqual(toValue: emailTextField.text!)
queryRef ? .observeSingleEvent( of: .value, with: {
  (snapshot) in
  for snap in snapshot.children {
    let userSnap = snap as!DataSnapshot
    let thechild = userSnap.key
    print(thechild + "Hi")
    if thechild != "" {
      theauth = 3
      print(thechild + "1")
    } else if self.password2.text == self.passwordTextField.text {
      theauth = 1
    } else {
      theauth = 2
    }
  }
  print(theauth)
})

提示:Asynchronous请阅读这篇文章,这篇文章是我专门为您写的:“我的代码中没有异步语句”是的,您有。@Rob我专门使用了术语“完成闭包”,以避免与其他闭包参数混淆。当然,并非所有(甚至不是大多数)闭包都是完成闭包。但这些都意味着该方法是异步的,至少我使用的术语是“完成闭包”。我的错误是没有明确我所说的“完成关闭”的具体含义。将打印内容放在最后一个括号内是有效的。看起来很傻,但我没有意识到这些函数会异步运行。太棒了!如果您认为答案在将来对其他用户有帮助,请随意将其标记为正确答案。