加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

嵌套函数的好处是什么(一般来说/在Swift中)

发布时间:2020-12-14 02:26:55 所属栏目:百科 来源:网络整理
导读:我刚刚学习了一些 Swift,我遇到了关于嵌套函数的部分: 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 o
我刚刚学习了一些 Swift,我遇到了关于嵌套函数的部分:

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.

从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.

哦,我完全不同意.如果需要第二个函数的唯一位置在第一个函数内部,那么将它保持在第一个函数内部则更有条理.

现实生活中的例子:http://www.apeth.com/swiftBook/ch02.html#_function_in_function

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

但是,本地函数允许您执行的任何其他方式无法轻松完成的关键是您可以实时形成函数(因为函数是闭包)并从外部函数返回它.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读