2017-03-23 72 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() 
}