How to create local scopes 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.)

Leave a Comment