How to call escaping function one after another only when condition matches in swift?

Viewed 107
func conditionalCalling() {

if 1==1 {
    hitFirstAPI {
        if 2==2 {
            hitSecondAPI {
                if 3==3 {
                    hitThirdAPI {
                    }
                }
            }
        }
        else if 3==3 {
            hitThirdAPI {
                
            }
        }
    }
}
else if 2==2 {
    hitSecondAPI {
        if 3==3 {
            hitThirdAPI {
                
            }
        }
    }
    
}
else if 3==3 {
    hitThirdAPI {
        
    }
}

}


    func hitFirstAPI(done: @escaping ()->Void) {
        
    }
    func hitSecondAPI(done: @escaping ()->Void) {
        
    }
    func hitThirdAPI(done: @escaping ()->Void) {
        
    }

Above code gives a simple idea of my questions, in simple words, if condition matches I want to call functions one after another if not check for next condition and if that's true call the next function and so on...

How can I do that in minimum lines of code?

My thought initially:

func conditionalCaling() {
    if 1==1 {
        hitFirstAPI {
            
        }
    }
    if 2==2 {
        hitSecondAPI {
            
        }
    }
    if 3==3 {
        hitThirdAPI {
            
        }
    }
}

Although this approach will call function only if condition matches, it will call all functions together, NOT after one function escapes closure block.

Topmost code seems to be the solution but I want to do that in minimum lines of code, is there any other better approach than if else statements all around ??

1 Answers

You can refactor your first attempt into smaller reasonable chunks like this.

import Foundation

func conditionalCalling() {
    initiateFlow {
        print("Done!")
    }
}
func initiateFlow(done: @escaping ()->Void) {
    if 1==1 {
        hitFirstAPI { initiateSecondAPI(done: done) }
    } else {
        initiateSecondAPI(done: done)
    }
}
func initiateSecondAPI(done: @escaping ()->Void) {
    if 2==2 {
        hitSecondAPI { initiateThirdAPI(done: done) }
    } else {
        initiateThirdAPI(done: done)
    }
}
func initiateThirdAPI(done: @escaping ()->Void) {
    if 3==3 {
        hitThirdAPI(done: done)
    } else {
        done()
    }
}
func hitFirstAPI(done: @escaping ()->Void) {}
func hitSecondAPI(done: @escaping ()->Void) {}
func hitThirdAPI(done: @escaping ()->Void) {}

In above method, your checks are not unnecessarily repeated and it still does what you wanted in your first attempt (original flow).

Related