As noted in the comments, anonymous nested areas in C are often a sign that you could write better code. For example, instead of simply doing work in a nested area that ultimately sets self.titleLabel , you could instead assign the result of evaluating the built-in closure:
self.titleLabel = { let label = UILabel() label.text = "some text" // ... set other properties ... self.addSubview(label) return label }()
This not only saves the label as a beautiful short name, which only refers to the piece of code that creates and sets it up, but it saves this piece of code associated with the property for which it creates the value. And it's more modular, because you could replace all closures with a call to some other shortcut function, if it ever became useful to adjust this code.
If you do this often, you can try creating a generic function that allows you to shorten your build code to this:
self.titleLabel = makeSubview(UILabel()) { label in label.text = "some text"
But I will leave the definition of such a function as an exercise for the reader .;)
As stated in Jean-Philippe Pellet's answer , in Swift 2.0, and later the do construct is an explicitly language-provided way to do this. (And the functional solution that he offers is a decent option for those who are still using Swift 1.x.)
Another Swift 1.x solution - without defining a new function - is to (explicitly) throw out the result of the closure immediately executed:
_ = { print("foo") }()
rickster Jan 27 '15 at 18:29 2015-01-27 18:29
source share