3

I need to create a self-executing block in Swift, similar to what we had in Objective C:

{
  /* statements */
}

However the same construct in Swift yields "braced block of statements in unused block".

Khanh Nguyen
  • 11,112
  • 10
  • 52
  • 65
  • Your (Objective-)C example is *not* a block and *not* a "immediately invoked function" or "self-executing block". It is just parentheses introducing a local scope. If that is what you are looking for then your question is a duplicate. – If your question is about ["Immediately-invoked function expressions"](http://en.wikipedia.org/wiki/Immediately-invoked_function_expression) then @jrturtons's answer should answer it. – Perhaps you can clarify your question and/or title. – Martin R Jan 10 '15 at 10:55

1 Answers1

2

At the moment, I use:

if true {
  /* ... */
}

Any better solution is welcome.

UPDATE 2: Swift 2 now has a new control structure do:

do {
    /* ... */
}

UPDATE: Another answer is found here:

func locally(work: () -> ()) {
    work()
}

...

locally {
    /* ... */
}

This looks nice, except that due to Swift's rules, you have to use self.property instead of just property inside the block.

Community
  • 1
  • 1
Khanh Nguyen
  • 11,112
  • 10
  • 52
  • 65
  • I think this is the best you can get. Objective-C like scope block is not possible as the syntax is taken by the closures. – Kirsteins Jan 10 '15 at 09:45