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

嵌套函数的好处是什么(一般来说在Swift中),第1张

概述我刚刚学习了一些 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 functi 我刚刚学习了一些 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

总结

以上是内存溢出为你收集整理的嵌套函数的好处是什么(一般来说/在Swift中)全部内容,希望文章能够帮你解决嵌套函数的好处是什么(一般来说/在Swift中)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1089742.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存