在 Swift中,据我所知,闭包保留了他们的环境,而普通的功能却没有. 考虑下面的f(返回一个函数)和h(返回一个闭包). f()()和h()()都返回3.为什么f()()不会导致运行时错误? func f() - () - Int { l
考虑下面的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()会捕获值.