Swift: Execute defer statement on exit of parent/caller's scope instead of scope of current functions

Viewed 27

I understand that in Swift, code in the defer block would execute immediately after the current scope has exited, regardless of the control flow in the function below, for example:

func someFunc() {
    defer {
        print("Prints when someFunc() exits, no matter the control flow below")
    }
    // Arbitrary control flow (if, else with returns. Completion calls, etc.)
}

However, is it possible for the defer block in a callee to execute after the scope of its caller has exited? For example:

func calleeFunc() {
    defer {
        print("Called when callerFunc() is exited!")
    }
}

func callerFunc() {
    calleeFunc()
    print("This will print BEFORE \"Called when callerFunc() is exited!\")
}

Thanks!

0 Answers
Related