IIFE在Swift语言中

Zac*_*yle 4 iife swift

在javascript中我们经常使用IIFE.就像是

(function() {
    ...do stuff to avoid dirtying scope.
}());
Run Code Online (Sandbox Code Playgroud)

Swift中有闭包,函数是一等对象.我的问题是:Swift中是否有相同的IIFE?

jam*_*ack 8

这里接受的答案是误导性的 - 有一种更容易和更优雅的方式来创建一个立即调用的闭包表达式(IICE).

有关语法的所有详细信息和差异,请参阅Apple Swift文档以获取闭包.有关简单演示,请参阅:

let dateString: NSString = { date in
  let timestampFormatter = NSDateFormatter()

  timestampFormatter.dateStyle = .MediumStyle
  timestampFormatter.timeStyle = .MediumStyle

  return timestampFormatter.stringFromDate(date)
}(NSDate())
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Enr*_*ata 4

当然,您可以使用闭包实现类似的效果:

func iife( f : () -> () ) {
 f()
}
Run Code Online (Sandbox Code Playgroud)

然后说

iffe { 
// my code here
}
Run Code Online (Sandbox Code Playgroud)

如果你真正需要的只是一个作用域,而 Swift 不支持使用 {..} 作为“作用域运算符”,你总是可以这样做

if 1 == 1 {
// oh, look, a scope :-)
}
Run Code Online (Sandbox Code Playgroud)

作为达到相同效果的不太花哨的方法。如果您尝试使用 RAII 模式,则需要依靠 ARC 来清理,或者使用闭包

if true {
    // should also work instead of if 1 == 1
}
Run Code Online (Sandbox Code Playgroud)