Reputation: 709
I saw a declaration which confuses me. ( the grammar here)
static var dateFormatter: NSDateFormatter = {
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
To declare a variable, it looks like it uses a function(initializer) to create one. Since I am not familiar with closure in Swift, I found some useful tutorial. However, the example above seems to not fit in any of them. ref: http://fuckingclosuresyntax.com/ Any suggestions, references, or tutorial will be appreciated.
Upvotes: 4
Views: 2982
Reputation: 818
As @findall said in the comments, you are basically creating a function and executing it.
To clarify the syntax, I'll try to create an example in JavaScript.
Consider this code snippet:
//creates a global variable
var globalString = "Very important global string";
This string will be created and stored in memory as soon as this line of code is interpreted. Now compare it to this other implementation:
//also creates a global variable
var globalString = function() {
return "Very important global string";
};
The second implementation does not create a string, but creates a function that ultimately produces a string.
In Swift, when you declare a variable with the {...}()
syntax, you are actually doing something similar to Example #2.
When would it be useful to declare a variable in such way? When the declaration would require some extra setup to take place.
In the example posted in the question, an NSDateFormatter may need a few extra steps to be instantiated the way your app expects it to behave. In other words:
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
}
}
This example is quite nicely replaced by:
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!
}
}
Upvotes: 6