Skip to content

Instantly share code, notes, and snippets.

@cemaleker
Last active July 30, 2018 20:17
Show Gist options
  • Save cemaleker/42a6c2c5d1dd0ff011bcddbeac8b7b93 to your computer and use it in GitHub Desktop.
Save cemaleker/42a6c2c5d1dd0ff011bcddbeac8b7b93 to your computer and use it in GitHub Desktop.
How swift defer captures
var baz: String?
func deferSomething(_ quux: inout String?) {
var foo: String
quux = "uier"
defer { print("__\(foo)__\(baz)__\(quux)__") }
quux = "grault"
foo = "bar"
}
func dontDeferSomething(_ quux: inout String?) {
var foo: String
quux = "uier"
quux = "grault"
foo = "bar"
{ print("__\(foo)__\(baz)__\(quux)__") }()
}
baz = "qux"
var quux: String? = "corge"
[deferSomething, dontDeferSomething].forEach({ $0(&quux) })
quux = "garply"
@cemaleker
Copy link
Author

Here's the output for the curious

__bar__Optional("qux")__Optional("grault")__
__bar__Optional("qux")__Optional("grault")__

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment