Swift - return 闭包中的变量

Swift - return variable from within closure

具有以下功能。在线程执行完成后,我正在寻找 return 作为 Int 的函数结果。它正在从外部设备查询变量。当我调用函数 get 变量时,我立即收到结果 -1,几秒钟后我从完成线程收到结果。我怎样才能重新处理它,以便在实际值 returned 之前没有结果 returned? 仍然是 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
}

也许你可以自己使用完成块:

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)
    }
}

另一种方法是使用Promises,看看这个实现: https://github.com/FutureKit/FutureKit

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