嵌套函数有什么好处(一般来说/在Swift中) [英] What is the benefit of nesting functions (in general/in Swift)

查看:220
本文介绍了嵌套函数有什么好处(一般来说/在Swift中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


函数可以嵌套在函数中。嵌套函数可以访问在外部函数中声明的变量。您可以使用嵌套函数将代码组织到一个长或复杂的函数中。


here

我能看出的唯一好处是你有权访问在外部函数中声明的变量,但这似乎



有什么想法?

解决方案

>


因此,如果声称的好处是组织代码,为什么不在外部函数之外单独使用嵌套函数呢?对我来说,这看起来更有条理。


哦,我完全不同意。如果唯一需要第二个函数的地方是第一个函数的内部,那么把它放在第一个函数内部会更有组织。



Real这里的例子: http://www.apeth.com/swiftBook/ch02.html# _function_in_function



此外,函数中的函数具有范围内的本地环境。嵌套函数内部的代码可以查看在嵌套函数声明之前声明的局部变量。这可以比传递一堆参数更方便和自然。



然而,本地函数允许您执行的你不能以其他任何方式做,就是你可以实时地形成函数(因为一个函数是一个闭包),并从外层函数中返回它。



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

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?

解决方案

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

这篇关于嵌套函数有什么好处(一般来说/在Swift中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆