-2

I have some external SDK library that makes IO calls (either networking or database) in the form of blocks, like so:

SomeClass.doWork(success: {}, failure: {})

Now I need to chain about 60 different calls because we are working on data replication where each operation is distinct enough that it's not the same, but the principle is there -> all of these take a success and a failure blocks.

What is the best way to organise this spaghetti:

let failureBlock: () -> Void = { // something
}

SomeClass.doWork(success: { [unowned self] in
   self.runChecks(success: {
       SomeOtherClass.somethingElse(success: { 
           SomeClass.doWork(success: { [unowned self] in
              self.doMore() ///... and on and on she goes
           }, failure: failureBlock)
       }, failure: failureBlock)
    }, failure: failureBlock)
}, failure: failureBlock)

Update I am concerned with performance and memory management over legibility as my stack traces look quite ugly with lots of thunk and closure in them :/

zaitsman
  • 384

1 Answers1

0

You can store closures in a variable.

Let task60 = { Someclass.dowork (success: ..., failure: ...}
Let task59 = { Someclass.dowork (success: task60, failure: ... }
...
Let task0 = { Someclass.dowork (success: task1, failure: ... }
Task0()

There’s absolutely no need to worry about performance due to use of closures.

gnasher729
  • 44,814
  • 4
  • 64
  • 126