Swift - 从闭包内返回变量

时间:2016-10-06 11:46:32

标签: ios swift swift3 ios10

具有以下功能。我希望在完成线程执行后将函数的结果作为Int返回。它正在查询外部设备的变量。当我调用函数get变量时,我立即收到结果-1,然后几秒后我从完成线程收到结果。如何重新处理此项,以便在返回实际值之前不返回任何结果? 还是一个使用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
}

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

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

来创建getvariable函数
相关问题