在Swift中嵌套函数时,如何将布尔值返回给外部函数? [英] How to return a bool to the outside function when you have nested functions in Swift?

查看:60
本文介绍了在Swift中嵌套函数时,如何将布尔值返回给外部函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个函数,该函数具有一个连接到Firebase数据库的内部函数.该函数返回布尔值,但我需要根据Firebase数据库中的内容返回true或false.所以基本上我需要在Firebase函数内部返回true或false,问题是当我实际上试图返回到外部函数时,它认为我正在尝试返回到Firebase函数.

So I have a function I have that has an inner function that connects to a Firebase database. the function returns a bool but I need the to return true or false based on whats inside the Firebase database. So basically I need to return true or false inside of the Firebase function the problem is it thinks that I am trying to return to the Firebase function when I am actually trying to return to the outside function a simple example is this

func someOtherFunc(name: String, lastname: String){


}
func someFunc(name: String, lastname: String) -> bool {
    someOtherFunc(name: name, lastname: lastname) {
        if name == "George" {
        return true


        } else {
        return false // will not work because some other func does not return a value
        }


    }
}

这是我需要修复的代码,它比上面的函数复杂一些,因为内部Firebase函数是异步运行的(在后台),因此该函数内部的所有代码都需要同步运行以返回正确的值

here is the code that I need fixed which is a little more complicated than the above function because the inner Firebase function runs asynchronously(in the background) and so all the code inside the function needs to run synchronously to return the correct value

这是我的职责

func takeAwayMoney(_ howMuch: String) -> Bool{
        if let notMuch = Int(howMuch) {

            let userID = FIRAuth.auth()?.currentUser?.uid
            datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
                // Get user value
                let value = snapshot.value as? NSDictionary
                let money = value?["money"] as? String ?? ""

                //convert money to int
                if let conMoney = Int(money) {
                    var conMoreMoney = conMoney
                    if conMoreMoney < notMuch {
                        print(" sorry you don't have enough money")
                        return false
                    } else {
                        conMoreMoney -= notMuch
                        let values = ["money": String(conMoreMoney)]

                        //update the users money
                        self.datRef.child("User").child(userID!).updateChildValues(values)
                        return true //doesn't work because of example above
                    }

                }

                // ...
            }) { (error) in
                print(error.localizedDescription)
            }
        }
    }

此代码无法编译,因为主函数没有返回值.

This code does not compile because there is no return values to the main function.

我知道解决此问题的真正困难的方法是在函数顶部初始化值,这将是用户的钱,然后在分派几秒钟后对其进行检查,然后可以返回值,但是我知道必须有另一种方法,因为这种方法会引起很多问题.

I know the really hard way to fix this would be to initialize values at the top of the function that would be the money of the user then check it after dispatching it for a couple of seconds then you could return the values, but I know there must be another way because this way would cause a lot of problems.

推荐答案

根本原因是 takeAwayMoney 是同步的,但它使用了异步的 observeSingleEvent .

The root cause is that takeAwayMoney is synchronous, but it uses observeSingleEvent, which is asynchronous.

解决此问题的正确"方法是使 takeAwayMoney 返回Void,但采用一个完成函数,该函数将异步给您bool,如下所示:

The "right" way to solve this is to make takeAwayMoney return Void, but take a completion function that will give you the bool asynchronously, like this:

func takeAwayMoney(_ howMuch: String, completion: @escaping (Bool)->()) -> Void {

/// When you want to "return" the bool, call the completion. e.g.:
// ...
                if conMoreMoney < notMuch {
                    print(" sorry you don't have enough money")
                    completion(false)
                    return // if you want to stop processing
                }
// ...

}

如果您不能执行此操作,则takeMoney需要等待完成完成,然后使用信号量使它们彼此通信.您不只是等待几秒钟.参见以下示例:

If you cannot do this, then takeMoney needs to wait for the completion to finish and you use semaphores to have them communicate with each other. You do not just wait a couple of seconds. See this for an example:

信号量以同步运行异步方法

这篇关于在Swift中嵌套函数时,如何将布尔值返回给外部函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆