I'm regularly using local scopes in Objective-C to make naming clearer.
{ UILabel *label = [[UILabel alloc] init]; [self addSubview:label]; self.titleLabel = label; }
I am trying to rewrite this code in Swift like this:
{ let label = UILabel() self.addSubview(label) self.titleLabel = label }
This gives me get the following error:
Error: Braced block of statements is an unused closure.
So how can I create a local scope in Swift?
Update: In Swift 2.0, you just use the do
keyword:
do { let label = UILabel() self.addSubview(label) self.titleLabel = label }
This was true for Swift pre-2.0:
You can define something similar to this:
func locally(@noescape work: () -> ()) { work() }
And then use such a locally
block as follows:
locally { let g = 42 println(g) }
(Inspired by locally
in Scala's Predef object.)
As of Swift 2, you can create a local scope with the do
-statement:
do { let x = 7 print(x) } print(x) // error: use of unresolved identifier 'x'
The main use-case however seems to be error-handling with do-try-catch, as documented in "Error Handling" in "The Swift Programming Language", for example:
do { let jsonObj = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) // success, do something with `jsonObj`... } catch let error as NSError { // failure print("Invalid JSON data: \(error.localizedDescription)") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With