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

前端 未结 3 1878
天命终不由人
天命终不由人 2020-12-06 03:04

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 acc

3条回答
  •  萌比男神i
    2020-12-06 03:52

    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

提交回复
热议问题