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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。