简体   繁体   English

Swift-从闭包内部返回变量

[英]Swift - return variable from within closure

have the following function. 具有以下功能。 I am looking to return the result from the function as an Int following the completion of the thread execution. 我希望在线程执行完成后以Int形式从函数返回结果。 It is querying a variable form an external device. 它正在从外部设备查询变量。 When I call the function get variable, I immediately receive the result -1, then several seconds after this I receive the result from the completion thread. 当我调用函数get变量时,我立即收到结果-1,然后在几秒钟后从完成线程收到结果。 How can I re-work this so no result is returned until the real value is returned? 我该如何重做,直到返回实际值才返回结果? still a noob with Swift3 and GCD..thanks 还是Swift3和GCD的菜鸟..谢谢

func getVariable(variableName: String) -> Int {
    var res: Int = -1
    print (deviceOK)
    if deviceOK {
        DispatchQueue.global(qos: .default).async {
            // logging in
            (self.deviceGroup).wait(timeout: DispatchTime.distantFuture)
            (self.deviceGroup).enter()

            self.myPhoton!.getVariable(variableName, completion: { (result:Any?, error:Error?) -> Void in
                if let _ = error  {
                    print("Failed reading variable " + variableName + " from device")
                } else {
                    if let res = result! as? Int {
                        print("Variable " + variableName + " value is \(res)")
                        self.deviceGroup.leave()
                    }
                }
            })
        }
    }

    return res
}

Maybe you can use completion block yourself: 也许您可以自己使用完成阻止功能:

func getVariable(variableName: String, onComplete: ((Int) -> ())) {
    var res: Int = -1
    print (deviceOK)
    if deviceOK {
        DispatchQueue.global(qos: .default).async {
            // logging in
            (self.deviceGroup).wait(timeout: DispatchTime.distantFuture)
            (self.deviceGroup).enter()

            self.myPhoton!.getVariable(variableName, completion: { (result:Any?, error:Error?) -> Void in
                if let _ = error  {
                    print("Failed reading variable " + variableName + " from device")
                } else {
                    if let res = result! as? Int {
                        onComplete(res)
                        print("Variable " + variableName + " value is \(res)")
                        self.deviceGroup.leave()
                    }
                }
            })
        }
    } else {
        onComplete(res)
    }
}

Another approach is to use Promises, take a look at this implementation: https://github.com/FutureKit/FutureKit 另一种方法是使用Promises,看一下此实现: https : //github.com/FutureKit/FutureKit

您应该使用完成处理程序来使getvariable函数而不是返回Int。

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

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