What is the advantage of defining a constant by closing in Swift 3

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

I saw many people who defined the source code for Swift. I'm just wondering what is the use of this?

+4
source share
1 answer

In this case, there is no benefit, but if the variable in question is a type of value, then the advantage will be that you can execute some mutating installation code and still get a constant from it.

It also allows you to hide temporary variables that are only needed to initialize the constant, since they will only exist inside the closure area.

+2
source

Source: https://habr.com/ru/post/1678480/


All Articles