返回一个函数vs返回一个闭包

前端之家收集整理的这篇文章主要介绍了返回一个函数vs返回一个闭包前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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()会捕获值.

猜你在找的Swift相关文章