【发布时间】:2016-10-06 11:46:31
【问题描述】:
具有以下功能。我希望在线程执行完成后将函数的结果作为 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
}
【问题讨论】:
-
在后台线程调用函数。