objective-cswiftobjective-c-blockschainingswift-block

Chaining nullable blocks in Objective-C and in Swift?


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.


Solution

  • 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.