I'm developing an app that fetches data from few different APIs using Alamofire (each call is done using a function). Then I have to collect all of the results (Double type in my case) to one array to calculate the average.
As long as Alamofire uses asynchronous calls, it is impossible to simply append new value to an array from inside of call.
Here is a function that calls each of functions responsible for fetching data by Alamofire:
func collectData() {
fetchFromFirstAPI()
fetchFromSecondAPI() //etc.
}
And here is an example of one of these functions:
func fetchFromFirstAPI() {
let APIKey = "XXXXXXXXX"
let APIURL = "http://urlapi.com/api" as URLConvertible
let parameters: Parameters = ["APPKEY": APIKey]
Alamofire.request(APIURL, method: .get, parameters: parameters, encoding: URLEncoding.default).validate().responseJSON { response in
switch response.result {
case .success(let data):
let json = JSON(data)
if let result = json["main"]["value"].double {
myArray.append(result)
} else {
print("error")
}
case .failure:
print("error")
}
}
}
And the array:
var myArray: [Double] = []
How to deal with it?