IIFE in Swift Language

iife, swift

Solution

You can achieve a similar effect using closures, sure:

func iife( f : () -> () ) {
 f()
}

And then say

iffe { 
// my code here
}

If all you truly need is a scope, while Swift does not support the use of {..} as a "scoping operator", you can always do

if 1 == 1 {
// oh, look, a scope :-)
}

as a less fancy way to achieve the same effect. If you're trying to use RAII patterns, you will need to either rely on ARC to cleanup for you, or use a closure though

if true {
    // should also work instead of if 1 == 1
}

Problem

In javascript we use IIFEs a lot. Something like ``` (function() { ...do stuff to avoid dirtying scope. }()); ``` There are closures in Swift, and functions are first class objects. My question is: are there equivalent IIFEs in Swift?

Original source