Skip to content

Instantly share code, notes, and snippets.

@lbrndnr
Created February 8, 2015 17:49
Show Gist options
  • Save lbrndnr/f54d81079007477744c7 to your computer and use it in GitHub Desktop.
Save lbrndnr/f54d81079007477744c7 to your computer and use it in GitHub Desktop.
Why do nested function not work within closures?
func functionWithClosure(closure: () -> ()) {
closure()
}
func topFunction() {
let button = UIButton()
let image = UIImage()
func nestedFunction() {
button.setImage(image, forState: .Normal)
}
nestedFunction() // works
functionWithClosure {
nestedFunction() // doesn't work
}
}
@zwaldowski
Copy link

Though it's a little dense, the error you get here is descriptive: "Cannot reference a local function with capture from another local function". See this Stack Overflow answer.

The key is that nested functions and closures capture data from their surroundings a little bit differently. Closures are always work on the assumption that they can be called from another context; functions don't.

There might be actual limitations I'm not aware of, but you can think of it as artificial: you get into weird situations with memory when closures capture functions, since functions are always meant to exist within their parent scope.

(FWIW, it works if you pass nestedFunction directly to functionWithClosure, like functionWithClosure(nestedFunction).)

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