I just started learning Javascript
and ran across an Immediately Invoked Function Expression
or IFFE
for short. The parentheses
at the end immediately invokes
the function
.
var greetingsObject = function(name){
return 'Hello' + name;
}(); //will return Hello undefined
In Swift
I'm also learning how to programmatically
create objects. I create a UILabel
var greetingsObject: UILabel = {
let label = UILabel()
label.text = "Hello " + nameTextField.text!
return label
}()
My question is does the parentheses
at the end of the Swift
object work the same way as the one at the end of the JS
IFFE
? If it doesn't call
the function
then what does it do?
I first to point out a bug with your example: your code reference nameTextField
within the initializer for greetingObject
. There's no guarantee what property will be initialized first so you can't reference another property within the init closure.
Having said that, it works the same in Swift as Javascript. greetingsObject
will be initialized when you initialize the class instance. This pawttern is usually employed when you want the property to be initialzed only once and shared among multiple instances.
Swift also extended the concept with an optional lazy
modifier. With lazy
, it will initialize the property the first time you reference it.
class ViewController : UIViewController {
lazy var greetingsObject: UILabel = {
print("Initialzing greetingsObject")
let label = UILabel()
label.text = "Hello World"
return label
}()
}
let vc = ViewController() // `greetingsObject` is not yet initialized
print("First reference to greetingsObject")
vc.greetingsObject.text // it will be initialized here