2016-10-06 6 views
-1

には、以下の機能があります。スレッドの実行が完了した後、関数の結果をIntとして返すようにしています。これは、外部デバイスの変数を照会しています。関数get変数を呼び出すと、すぐに結果-1が返され、その後、完了スレッドから結果を受け取った後数秒が経過します。これを再実行すると、実際の値が返されるまで結果は返されません。 はまだSwift3とGCD..thanks閉鎖内からスイフトリターン変数

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 
} 
+0

バックグラウンドスレッドで関数を呼び出します。 –

答えて

0

Intを返す代わりに、完了ハンドラを使用してgetvariable関数を作成する必要があります。

4

とのnoobたぶん、あなたは自分自身をブロック補完を使用することができます。

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

別のアプローチは、この実装を見てみましょう、約束を使用することです: https://github.com/FutureKit/FutureKit