When I read an open source code, I often find a structure like this:

var textLabel:UILabel = {
    let label = UILabel()
    label.backgroundColor = .red
    return label
}()Copy the code

It compiles, it runs, so of course the syntax is correct, you can read it from the text and you know what the code is doing, but what syntax is it?

Since we are concerned with grammatical structure, the simplification looks like this, which does not affect the problem we are studying, but is much simpler:

  var a = {return 42}Copy the code

So, we can print it to verify what it is, right?

    var a = {return 42}
    print(a)//(Function)
    print(a())//42Copy the code

It turns out to be

(Function)
42Copy the code

This means that {} defines a closure that takes no parameters. Although closures are often used as function arguments, direct calls are also available. Plus () specifies the function. The definition and invocation of this function is super flexible and feels like a JavaScript function.