考虑下面的f(返回一个函数)和h(返回一个闭包). f()()和h()()都返回3.为什么f()()不会导致运行时错误?
func f() -> () -> Int { let a = 3 func g() -> Int { return a } return g } func h() -> () -> Int { let a = 3 return { () in a }}解决方法 你所写的并不完全正确,因为根据 documentation:
Global functions are closures that have a name and do not capture any values.
nested functions are closures that have a name and can capture values from their enclosing function.
Closure Expressions are unnamed closures written in a lightweight Syntax that can capture values from their surrounding context.
所以g()会捕获值.
总结以上是内存溢出为你收集整理的返回一个函数vs返回一个闭包全部内容,希望文章能够帮你解决返回一个函数vs返回一个闭包所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)