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