Sco*_*t S -1 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
}
Run Code Online (Sandbox Code Playgroud)
小智 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)
}
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用Promises,看看这个实现:https: //github.com/FutureKit/FutureKit
| 归档时间: |
|
| 查看次数: |
692 次 |
| 最近记录: |