在 Swift中,据我所知,闭包保留了他们的环境,而普通的功能却没有.
考虑下面的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()会捕获值.
@H_403_38@
总结
以上是编程之家为你收集整理的返回一个函数vs返回一个闭包全部内容,希望文章能够帮你解决返回一个函数vs返回一个闭包所遇到的程序开发问题。
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
发表评论