I am confused surrounding the syntax for a completion handler in swift 3.
In the function below, after parsing an xml
file from a web service call, it should return a variable (an array [String:String]
).
My attempt is below, but obviously it is incorrect.
enum HistoryKey {
case success([String:String])
case failure(String)
}
private func getHistoryKeys(searchterm: String, completion: @escaping () -> HistoryKey) {
let url = PubmedAPI.createEsearchURL(searchString: searchterm)
let request = URLRequest.init(url: url as URL)
let task = session.dataTask(with: request) { (data, response, error) in
if let theData = data{
let myParser = XMLParser.init(data: theData)
myParser.delegate = self
myParser.parse()
}
}
task.resume()
if keys.isEmpty {
return .failure("no historyKeyDictionary")
}else{
return .success(keys)
}
}// End of func
I want to use this function as follows
let result = self.getHistoryKeys(searchTerm)
Something like that. Change
@escaping
declaration and do a completion instead of return.Hope it helps.
Return the result as an argument in the completion handler:
And call it like this:
Two issues:
HistoryKey
instance and has no return value so the signature must be the other way round.To be able to parse the received data outside the completion block return the
data
on successand call it
From what I can see, it should be
Also
completion(.failure("no historyKeyDictionary"))
orcompletion(.success(keys))
should be used instead ofreturn
You are not using
completion
block.Use it like:
Then you can call this function as:
Swift 4.2
OR