简体   繁体   English

Swift-在重复循环中使用闭包

[英]Swift - Using a closure inside a repeat loop

I am trying to implement a user registration system and I need to know whether a user id (generated randomly) has already been assigned to another user or not. 我正在尝试实施一个用户注册系统,我需要知道一个用户ID(随机生成)是否已经分配给另一个用户。 To do so, I connect my Firebase database and use the observer() method to check to availability of the generated id. 为此,我连接了Firebase数据库,并使用observer()方法检查生成的ID的可用性。

However, since the Firebase database query runs asynchronously and I can only know the result once the query returns, I am not able to use the correct return value from within the calling method. 但是,由于Firebase数据库查询是异步运行的,并且查询返回后我只能知道结果,因此我无法在调用方法中使用正确的返回值。

My approach here is 我的方法是

repeat {
  id = generateUniqueId()
  check availability
} while (id is not unique)

The implementation I have is 我的实现是

var id:String
var test = true
repeat {
    id = generateId()
    ref.child("\(databaseReferenceName)").observe(.value) { (snapshot) in
        test = snapshot.hasChild("\(id)")
    }
} while (test == true)

This loop keeps running even though the test variable is set to false by the hasChild() method. 即使hasChild()方法将test变量设置为false ,该循环仍将继续运行。

How can I change the code so that I would be able to capture the right value of the test variable? 如何更改代码,以便能够捕获test变量的正确值?

I am using Swift 4.1 我正在使用Swift 4.1

Thanks 谢谢

You don't say, but I'm assuming the observe() function you're using is asynchronous, and will return before the work is done. 您没有说,但是我假设您正在使用的observe()函数是异步的,并且将在工作完成之前返回。 As PaulW11 says, you need to trigger the next round in the completion handler: 正如PaulW11所说,您需要在完成处理程序中触发下一轮:

func observeChildren() {
    var id:String
        id = generateId()
        ref.child("\(databaseReferenceName)").observe(.value) { (snapshot) in
            if snapshot.hasChild("\(id)") {
              observeChildren() //recursively call observeChildren again.
        }
}

Since the process is asynchronous the loop will run until hit the first test = false , but i think you need this recursive way until find an available id 由于该过程是异步的,因此循环将一直运行到命中第一个test = false为止,但是我认为您需要这种递归方式,直到找到可用的id

func checkID() {

       id = generateId()
       ref.child("\(databaseReferenceName)").observeSingleEvent(.value) { (snapshot) in
         let test = snapshot.hasChild("\(id)")

         if test {
           print("id exists")
           checkID() // check another one
         }
         else {
          print("this is the one \(id)")
         }
       }

}

another thing is that it should be observeSingleEvent instead of observe 另一件事是它应该是observeSingleEvent而不是observe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM