Anton Holmquist Anton Holmquist - 3 months ago 8
Swift Question

How to create local scopes in 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?

Answer

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

Comments