2017-07-31 45 views
0

這是我第一次在論壇上詢問,因爲我對編程相當陌生。For循環以隨機順序追加陣列

我正在嘗試使用BEMSimpleLineGraph在swift中創建歷史匯率圖,並使用AlomoFire從http://fixer.io/獲取數據。我使用一個for循環來循環到7天(只是爲了看看,如果我能得到它的工作),然後追加(或任何它被稱爲)的值稱爲xAxisData

func updateGraphData(timeInterval: Int){ 
    if selectedCurrency1 != nil && selectedCurrency2 != nil { // checking if both currencies have been selected 
     self.xAxisData.removeAll() // removing some default values 

     for i in 1...timeInterval { // don't know exactly if i'm doing this the optimal way? 
      print("passed") 
      let date = Date() 
      let dateComponents = Calendar.current.dateComponents([.month, .day,.year], from: date) //getting the the year(again, just to see if it's working) 
      historyURL = "http://api.fixer.io/\(dateComponents.year!.description)-03-0\(String(i))?base=\(selectedCurrency1!.rawValue)" //modifying the url to my needs 


      Alamofire.request(historyURL, method: .get).responseJSON { // requesting data 
       response in 
       if response.result.isSuccess{ 
        let json = JSON(response.result.value!) 
        self.xAxisData.append(json["rates"] [self.selectedCurrency2!.rawValue].doubleValue) // using SwiftyJSON btw to convert, but shouldn't this in theory append in the correct order? 
        print(json["date"].stringValue) // printing out the date 


       } 
       else{ 
        print("Error \(String(describing: response.result.error))") 
       } 
     } 

    } 
    } 
} 

CONSOLE數組:

[] 
2017-03-02 
2017-03-03 
2017-03-01 
2017-03-03 
2017-03-03 
2017-03-06 
2017-03-07 
[4.5359999999999996, 4.5316000000000001, 4.4739000000000004, 4.5316000000000001, 4.5316000000000001, 4.5133000000000001, 4.4844999999999997] 

我知道我犯了一個錯誤,使貨幣值翻倍,當它可能應該是一個浮動。如有需要,請隨時索取更多信息或以其他任何方式糾正我的錯誤,因爲我只是想學習。

我想輸出按時間順序,所以日期1,2,3,4,5,6,7而不是2,3,1,3,3,6,7。我正在使用多個已修改的網址,例如api.fixer.io/2017-03-01?base=GB。

謝謝!

+1

你想要什麼?你想對數據進行排序嗎 –

+0

你可以同時發起一系列的http請求,但不能保證他們會按照他們被解僱的順序完成。 –

+0

嗨,你究竟想要達到什麼樣的目標和輸出你爲什麼認爲這是錯誤的輸出。 如果您可以發佈您從http://api.fixer.io/生成的網址,這將會很有幫助。 –

回答

1

問題是,所有的網絡請求都是異步的,並不能保證它們將按照它們被調用的順序完成執行。因此,數組中的數據不按您調用請求的順序。

您可以使用串行DispatchQueue使您的請求以您調用它們的順序運行,但是,這會讓您的程序變慢,因爲它一次只執行一個請求,而不是並行運行所有請求。

對於這個特定問題,更好的解決方案是將完成處理程序內部的值插入到數組中,並將其添加到某個索引中,而不是隻追加它們。這樣,即使您不必同步API調用,也可以使訂購與API調用的訂單相同。或者,您可以將返回的值存儲在字典中,其中鍵將是您發出網絡請求的日期的字符串表示形式。

0
  • 例如

    struct Rate { 
        let currency : String 
        let date : Date 
        var value : Double 
    } 
    
  • 創建一個數組var historicalRates = [Rate]()創建一個結構。

  • for循環

    • 計算日期與Calendar API,你的方式得到麻煩溢出到下個月。例如,

      let calendar = Calendar.current 
      // set the date to noon to avoid daylight saving changes at midnight in a few countries 
      let today = calendar.date(bySettingHour: 12, minute: 0, second: 0, of: Date())! 
      
      let formatter = DateFormatter() 
      formatter.dateFormat = "yyyy-MM-dd" 
      
      for dayOffset in 0...7 { 
          let currentDate = calendar.date(byAdding: .day, value: dayOffset, to: today)! 
          let currentDateAsString = formatter.string(from: currentDate) 
          print(currentDate, currentDateAsString) 
      } 
      
    • 從當前日期創建Date

    • 用實際日期和名稱創建一個Rate實例,將它添加到historicalRates並將其傳遞給異步任務。
  • 在完成塊中分配比率value
  • 使用DispatchGroup在循環完成時得到通知。
  • 最後通過date排序historicalRates
+0

按日期排序,因爲在這種情況下字符串應該足夠了。 – user3441734

+0

謝謝,這有幫助! – user8288212