We often write code that returns early, but has to make sure a bit of code 
(e.g., a completion handler) is always called whenever we return, which seems 
like a great use case for defer. I started to write this:

func execute(with completion: ((Bool) -> Void)?) {
        var success = false
        defer {
                // should always execute with the current state of success at 
that time
                completion?(success)
        }

        guard … else {
                // completion is expected to be executed with false
                return
        }

        success = true

        // completion is expected to be executed with true
}

However, it seems that defer copies the state of success, which means any 
update to the variable is not respected, and the completion block is always 
called with false.

Is there a way to make this work? I could image to call a function within the 
defer block that evaluates the success (e.g., depending on the state of an 
instance variable), but using a local variable seems to encapsulate this a lot 
better.

Thanks for reading and any advice in advance.
Sebastian
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to