0

I need to have a possibility to write:

//if someCase1
block1(block2(block3()))
//if someCase2
block1(block3())
//if someCase3
block2(block3())

where blocks are some blocks of code. I saw a lot of examples but no one describes how to declare chaining and nullable blocks simultaneously (it seems nullable is required for this case).

How to solve this issue? Both Swift and Objective-C solutions are applicable.

Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49
  • Do you need to implement reactive programming? You should look at [`ReactiveCocoa`](https://github.com/ReactiveCocoa) or something then. – user28434'mstep Jun 17 '19 at 09:42

1 Answers1

0

In Swift, you can achieve this using closures.

Create 3 variables of type (()->()) namely - block1, block2, block3

  1. Call block2 inside block1
  2. Call block3 inside block2

Example:

let dispatchGroup = DispatchGroup()
dispatchGroup.notify(queue: .main) {
    print("All blocks executed")
}

dispatchGroup.enter()
let block3 = {
    print("block3 called")
    dispatchGroup.leave()
}

dispatchGroup.enter()
let block2 = {
    print("block2 called")
    block3()
    dispatchGroup.leave()
}

dispatchGroup.enter()
let block1 = {
    print("block1 called")
    block2()
    dispatchGroup.leave()
}

block1()

In the above code, I've used DispatchGroup for synchronous execution of all the blocks.

PGDev
  • 23,751
  • 6
  • 34
  • 88