简体   繁体   English

在Swift 3中通过闭包定义常量有什么好处

[英]What is the benefit of define constant by closure in Swift 3

let a: UIView = {
    let a = UIView()
    a.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    return a
}()

I saw a lot of people's Swift source code defining let as this way. 我看到很多人的Swift源代码以这种方式定义。 I just curious what is the benefit of this way? 我只是好奇这种方式有什么好处?

In this case, there is no benefit, but if the variable in question were a value type then the benefit would be that you could perform some mutating setup code and still get a constant out of it. 在这种情况下,没有任何好处,但如果有问题的变量是值类型,那么好处是您可以执行一些变异设置代码并仍然可以获得常量。

It also lets you hide temporary variables that were only needed to initialize the constant, since they'll only exist inside the closure's scope. 它还允许您隐藏仅需要初始化常量的临时变量,因为它们只存在于闭包的范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM