[swift-users] Defer with local variable's state

Sebastian Hagedorn sebastian at iosphere.de
Thu Aug 11 09:16:14 CDT 2016


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


More information about the swift-users mailing list