Search code examples
functionswiftconventionscode-organizationnested-function

What is the benefit of nesting functions (in general/in Swift)


I'm just learning some Swift and I've come across the section that talks about nesting functions:

Functions can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex.

From here

So if the purported benefit is to "organize the code", why not just have the nested function independently, outside of the outer function? That, to me, seems more organized.

The only benefit I can discern is that you "have access to variables that were declared in the outer function", but this seems trivial in comparison to the messiness of having nested functions.

Any thoughts?


Solution

  • So if the purported benefit is to "organize the code", why not just have the nested function independently, outside of the outer function? That, to me, seems more organized.

    Oh, I totally disagree. If the only place where the second function is needed is inside the first function, keeping it inside the first function is much more organized.

    Real-life examples here: http://www.apeth.com/swiftBook/ch02.html#_function_in_function

    Plus, a function in a function has the local environment in scope. Code inside the nested function can "see" local variables declared before the nested function declaration. This can be much more convenient and natural than passing a bunch of parameters.

    However, the key thing that a local function lets you do that you could not readily do in any other way is that you can form the function in real time (because a function is a closure) and return it from the outer function.

    http://www.apeth.com/swiftBook/ch02.html#_function_returning_function