【问题标题】:Trying to return value from firebase querysnaphsot completion handler inside function试图从函数内的firebase查询snaphsot完成处理程序返回值
【发布时间】:2021-11-03 04:18:00
【问题描述】:

我正在尝试为我的函数 validateFields() 返回从异步代码块(从我的完成处理程序)生成的值,但是我不知道该怎么做。

func validateFields() -> Bool
{
        //Other else if statements
        //...

        else if !(usernameTextField.text!.isEmpty)
        {
            var retVal = false
            
            isUnique { (bool) in
                retVal = bool
            }
            
            print("THIS IS THE RET VALUE: " + String(retVal))
            //this print statement does not return the correct value            

            if retVal == false { return retVal }
        }
        errorLabel.text = " "
        return true

}

如您所见,它不起作用,我需要在 isUnique 中返回 bool 以获取整个函数。

【问题讨论】:

    标签: swift asynchronous completionhandler


    【解决方案1】:

    您不能存储isUnique 的关闭结果然后立即返回它,因为isUnique 将花费完成任何任务所需的时间。

    您想要类似以下的内容,其中completion所有路径上被调用,但只调用一次:

    func validateFields(completion: (Bool) -> Void) {
        //Other else if statements
        //...
        if ... {
            /* ... */
        } else if !(usernameTextField.text!.isEmpty) {
            var retVal = false
    
            isUnique { (bool) in
                print("THIS IS THE RET VALUE: " + String(bool))
                completion(bool)
            }
        } else {
            errorLabel.text = " "
            completion(true)
        }
    }
    

    来电者:

    validateFields { result in
        print("result: \(result)")
    }
    

    【讨论】:

    • 所以我没有办法等到 isUnique 中的代码完成后再返回布尔值?
    • @EAO123 除非你想使用 Swift 5.5 并发 - 不。不能同步返回异步值
    • 如何更改我的代码以使用 Swift 5.5 并发来做到这一点
    • @EAO123 您只需要支持 iOS 15+,就可能无法启动。无论哪种方式 - Swift 5.5 中的 async/await 在功能上等同于上面的这个答案。你必须谷歌一些资源或观看 WWDC 会议来学习如何使用它,但上面的这个答案正是你想要的。当您不知道某件事需要多长时间时,如果没有返回值再次处于异步上下文中,就无法返回值。
    • 啊,我明白了。但是,我想出了如何使用 isUnique 而无需在函数中返回其值,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多