2017-03-23 39 views
1

起作用我需要这个阵列夫特通过阵列与返回

self.values.append(value) 

为了追加与值另一个阵列从上面的阵列^。几乎我需要传递一个数组到另一个函数的附加值。

func updateChartValues() -> (LineChartDataSet) { 

      self.recieveChartValues() 

      var entries: [ChartDataEntry] = Array() 

      for i in 0 ..< values.count { 

       entries.append(ChartDataEntry(x: Double(i), y: Double(values[i]), data: UIImage(named: "icon", in: Bundle(for: self.classForCoder), compatibleWith: nil))) 

如何获取从recieveChartValues()附加到updateChartValues的这些值?主要困惑是因为它们是从Firebase追加的。

func recieveChartValues() { 

     //Firebase Initialization 
     var ref: FIRDatabaseReference! 
     ref = FIRDatabase.database().reference() 

     ref.child("general_room_index").observeSingleEvent(of: .value, with: {(snap) in 
      print("error3") 



      if let snaps = snap.value as? [Any]{ 
       for val in snaps { 
        if let value = val as? Int{ 
         self.values.append(value) 
         //print(self.values) 
        } 
       } 
      } 

     }) 

    }//retrive values func 



func updateChartValues() -> (LineChartDataSet) { 

     self.recieveChartValues() 

     var entries: [ChartDataEntry] = Array() 

     for i in 0 ..< values.count { 

      entries.append(ChartDataEntry(x: Double(i), y: Double(values[i]), data: UIImage(named: "icon", in: Bundle(for: self.classForCoder), compatibleWith: nil))) 

      print("Enetrie ", entries) 



     } 



     self.dataSet = LineChartDataSet(values: entries, label: "Bullish vs. Bearish") 
     self.dataSet.mode = LineChartDataSet.Mode.cubicBezier 


     return dataSet 

    } 
+0

由于Firebase任务将异步完成,因此您需要将闭包传递给'recieveChartValues'并从Firebase完成关闭中调用该闭包。 – Paulw11

+0

您能否告诉我一个示例如何做到这一点 – codechicksrock

+0

我有点理解完成和关闭Im只是不知道如何实现他们与这两个功能,我需要一个例子le完全了解 – codechicksrock

回答

1

就像Paulw11说的那样,症结在于异步性。如果你只是做

recieveChartValues() 
updateChartValues() 

recieveChartValues()运行(并立即返回),然后updateChartValues()运行(使用self.values没有新的值被追加),然后完成关闭该追加的新值运行。

直接调用updateChartValues()在完成关闭,像这样:

ref.child("general_room_index").observeSingleEvent(of: .value, with: {(snap) in 
    ... 
    if let snaps = snap.value as? [Any] { 
     for val in snaps { 
      if let value = val as? Int{ 
       self.values.append(value) 
       updateChartValues() 
      } 
     } 
    } 
}) 

或封闭参数添加到recieveChartValues()和调用,当你得到一个新的值:

func recieveChartValues(_ completion: @escaping() -> Void) { 
    ... 
    if let snaps = snap.value as? [Any] { 
     for val in snaps { 
      if let value = val as? Int{ 
       self.values.append(value) 
       completion() 
      } 
     } 
    } 
} 

并调用recieveChartValues像这样:

recieveChartValues { self.updateChartValues() } 

您还可以将参数添加到完成关闭,因此您可以将接收到的值传递给它,如果你感兴趣的是:

func recieveChartValues(_ completion: @escaping (Int) -> Void) { 
    ... 
      if let value = val as? Int{ 
       self.values.append(value) 
       completion(value) 
      } 
    ... 
} 

然后您关闭将用新值被称为:

recieveChartValues { newValue in 
    print("Received \(newValue)") 
    self.updateChartValues() 
}