I'm using Apollo iOS to fetch GraphQL queries. I want to move the apollo.fetch() query closures to a separate function in a class. This class will contain a static reference to the apollo client as well as functions for performing GraphQL mutations and queries.
I'm trying the following:
static func fetchQueryResults() -> CountriesQuery.Data.Country?{
var myResult: CountriesQuery.Data.Country?
myResult = nil
apollo.fetch(query: countriesQuery) { (result, error) in
print(result?.data)
myResult = result?.data //this line causes error
}
return myResult
}
Whenever I add the line myResult = result?.data I get the error Generic parameter 'Query' could not be inferred.
However, when the line is commented out it works fine, but obviously the function is pointless. Eventually I would like to generalize this function so I could pass the query into it, but how do I get the data out of this basic closure?
In essence the question is, how do I "wrap" a closure in a function?
The point of this function is to be able to get the number of rows for the table view section in the function:
override func tableView(_ tableView:UITableView, numberOfRowsInSection section: Int -> Int{
return fetchQueryResults.count
}
However, the view loads before this function runs. I think this is because the apollo.fetch() is running asynchronously?
A couple things that might fix it:
Add
import Apolloto that Swift file. You probably already have it, but if you create yourapolloinstance using a static utility class, that could be possible.Drop the
, errorin your closure so it's just{ result in. I think that's older syntax that's in a lot of tutorials out there, but theerroris now part of theresultitself.By default, it runs
DispatchQueue.main, but you can use thefetch()function call and fill out which DispatchQueue you want it to run on (i.e. as you type "fetch" in xCode, autocomplete will actually show it as 2 different func signatures: one that hides all the params with default values, and a second one where you can explicitly fill out each param).In general, a good pattern for async loading data in a table view is: