I'd like to return some values after the long term operation is completed. But furthermore I'd like to split the logic and the gui.
For example; I have two classes
- SomeServices.swift which has a method named "getDataFromService..."
- MyTableViewController.swift which will display the result from "getDataFromService"
So, previously in Objective-C I've just add a method in SomeServices like this:
(void)getDataFromService:(void (^)(NSArray *, NSError *))completionBlock{ ...... }
In this method I've just called completionBlock(myData, myError)
to return my values to the tableviewcontroller.
What would be the equivalent closure which I have to define in SomeServices.swift and how will it be called in MyTableViewController?
I know how to call a simple closures like this one:
....({
responseData, error in
if(!error){
//Do something
}
})
But I don't have any ideas how to define a closure with a completionBlock equivalent.
Any help would be appreciated
The plus of closures are, that you can pass everything you want. Methods or functions - it doesn't matter.
You can pass a function within the parameters and just call it.
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/ch/jEUH0.l
The answer is in the language guide:
Assume you want to return a String. This is the syntax
Here is an example that takes two strings and concatenates them, and returns the result:
then you can do the following:
Here is how I use a singleton ServiceManager to achieve this.
Below is the example how I use the singleton class.
I hope this helps anybody looking for the same solution.