Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using defer inside if

Tags:

swift

I want to execute some code after the function exits only if some code succeed like this:

if object.open {
    defer {
        object.close()
    }
}
...
dome some stuff...
...
return
}

The problem is that the defer is executing right after the if condition. As I understand that is the correct behavior.

The question then is: It is possible to defer a code of block inside the if to run after the function complete. I tried nested defers but that did not work. Thanks for any help!

like image 863
mestor Avatar asked Sep 05 '26 02:09

mestor


1 Answers

By using defer, it is not possible to directly defer something to happen beyond the end of the current scope, e.g., that of the if condition you are in. It is possible, however, to defer something unconditionally and move the condition inside the defer:

defer {
    if object.isOpen { object.close() }
}

A more general solution along these lines would be something like this:

var deferred: (() -> Void)? = nil
defer { deferred?() }
if object.isOpen {
    deferred = { object.close() }
}

This more general solution would allow deferring different things based on different conditions, but obviously at most one at a time. To support more than one you could of course use an array:

var deferred = [(() -> Void)]()
defer {
    for f in deferred.reversed() { f() }
}
if object1.isOpen {
    deferred.append { object1.close() }
}
if object2.isOpen {
    deferred.append { object2.close() }
}

However, I strongly advise against this as it obfuscates the code flow and seems indicative of bad design elsewhere. Usually the reason to use defer is when you have multiple ways out of a scope and want to avoid copypasting the same clean-up code to all of them, but here you have multiple paths through the clean-up. I would try to isolate the paths leading to the different clean-up requirements.

like image 71
Arkku Avatar answered Sep 06 '26 19:09

Arkku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!