-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
  • 4
  • 13
  • 2
    Do you have any actual evidence that these closures are causing either a performance or memory management issue? – Philip Kendall May 22 '20 at 07:46
  • Does this answer your question? [Is micro-optimisation important when coding?](https://softwareengineering.stackexchange.com/questions/99445/is-micro-optimisation-important-when-coding) – gnat May 22 '20 at 08:31
  • You should look into "futures"/"promises". Swift has quite a few libraries that offer them, like `Combine` (which is built in by Apple), RxSwift, and PromiseKit – Alexander Oct 01 '20 at 23:21

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
  • 42,090
  • 4
  • 59
  • 119