【问题标题】:Swift - return variable from within closureSwift - 从闭包内返回变量
【发布时间】: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
}

【问题讨论】:

  • 在后台线程调用函数。

标签: ios swift swift3 ios10


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多