If anyone can think of another way to achieve what I'm trying to do, your thoughts are welcome!
To give you an idea, I have over 40 different functions that have signatures similar to these:
func getXFromServer(arg1: String, arg2: Int, arg3: Bool, completion: ((MyCustomResponse)->Void)? = nil)
func getYDataFromServer(completion: @escaping (Bool)->Void)
func getZDataFromServer(arg1: Int, completion: @escaping (MyGeneric<MyClass>)->Bool)
Some have arguments, some don't; some have a completion handler, and some are optional. All sorts of Types are passed around.
I'm trying to streamline the process of handling the server's response: currently it has a lot of repeated code, all doing pretty much the same thing, just with different argument values and types.
Because these functions are all asynchronous, I use completion handlers to handle the server data when it's retrieved. I want all the 'repeated code' to go in one function, let's call it handleServerResponse
: depending on the server response's value, I want to do more async stuff and be able to re-execute the same outer function
For example:
func getYDataFromServer(completion: @escaping (Bool)->Void)
{
session.dataTask(with: URLRequest()) { data, response, error in
handleServerResponse(){ valid //I want to pass 'getYDataFromServer(completion: completion)' here so that 'handleServerResponse' can determine whether to re-execute it or not, based on the server response
//do more stuff with Y server data
}
}.resume()
}
I am currently handling the re-execution outside of handleServerResponse
, like so:
func getYDataFromServer(completion: @escaping (Bool)->Void)
{
session.dataTask(with: URLRequest()) { data, response, error in
handleServerResponse(){ valid
if !valid
{
self.getXYZDataFromServer(){
getYDataFromServer(completion: completion)
}
return
}
//do more stuff with Y server data
}
}.resume()
}
This is a very simplistic version of the code, but as you can see it gets to a lot of repeated code very fast.
Thanks