Created
February 8, 2015 17:49
-
-
Save lbrndnr/f54d81079007477744c7 to your computer and use it in GitHub Desktop.
Why do nested function not work within closures?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 tofunctionWithClosure
, likefunctionWithClosure(nestedFunction)
.)