Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create local scopes in Swift?

Tags:

swift

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?

like image 393
Anton Avatar asked Jun 03 '14 09:06

Anton


2 Answers

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.)

like image 113
Jean-Philippe Pellet Avatar answered Sep 22 '22 18:09

Jean-Philippe Pellet


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)") } 
like image 37
Martin R Avatar answered Sep 19 '22 18:09

Martin R