带闭包的 Swift 变量声明

Yao*_*Yao 3 variables closures declaration swift

我看到一个令我困惑的声明。(这里的语法)

static var dateFormatter: NSDateFormatter = {
    var formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    return formatter
}()
Run Code Online (Sandbox Code Playgroud)

要声明一个变量,它看起来像是使用一个函数(初始化程序)来创建一个。由于我不熟悉 Swift 中的闭包,我找到了一些有用的教程。但是,上面的示例似乎不适合其中任何一个。参考:http : //fuckingclosuresyntax.com/ 任何建议、参考或教程将不胜感激。

小智 6

句法

正如@findall 在评论中所说,您基本上是在创建一个函数并执行它。

为了阐明语法,我将尝试在 JavaScript 中创建一个示例。

考虑这个代码片段:

示例#1

//creates a global variable
var globalString = "Very important global string"; 
Run Code Online (Sandbox Code Playgroud)

这行代码一被解释,这个字符串就会被创建并存储在内存中。现在将其与其他实现进行比较:

示例#2

//also creates a global variable 
var globalString = function() {
    return "Very important global string";
};
Run Code Online (Sandbox Code Playgroud)

第二个实现不创建字符串,而是创建一个最终生成字符串的函数。

在 Swift 中,当你使用{...}()语法声明一个变量时,你实际上是在做类似于Example #2 的事情。


用例

什么时候以这种方式声明变量会有用?当声明需要进行一些额外的设置时。

在问题中发布的示例中, NSDateFormatter 可能需要一些额外的步骤来实例化您的应用程序期望它的行为方式。换句话说:

class ThisClass {
    //if you do this, you'll then have to configure your number formatter later on
    static var dateFormatter = NSDateFormatter()
    
    func userFormatter() {
        //you probably want this setup to take place only once
        //not every time you use the formatter
        ThisClass.dateFormatter.dateFormat = "yyyy-MM-dd"
    
        //do something with the formatter
    }
}
Run Code Online (Sandbox Code Playgroud)

这个例子很好地替换为:

class ThisClass {
    static var dateFormatter: NSDateFormatter = {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()
    
    func userFormatter() {
        //do something with the formatter with no setup needed!
    }
}
Run Code Online (Sandbox Code Playgroud)