Home > Back-end >  What do you call this kind of parameter and is it thread safe?
What do you call this kind of parameter and is it thread safe?

Time:10-25

I have these parameters that are initialised only once like this:

private let dateFormatter: DateFormatter = {
  let formatter = DateFormatter()
  ...
  return formatter
}()

I'd like to know more about these sorts of parameters but not sure what you call them? And are they thread safe (assuming the type is)?

CodePudding user response:

I don't think they have any special name. You are initializing a variable by defining an anonymous function and calling that function, so I have termed this a define-and-call initializer. But that's unofficial.

The construct is very very common. It is particularly useful, as here, for making sure that something is created and configured just once (date formatters are expensive to create). It has no special thread related characteristics. It is as thread safe as the code you have omitted.

One thing to note is that if this is a property, the omitted code cannot refer to self unless you change let to lazy var. (There is, alas, no lazy let; I regard that as a serious hole in the language.)

  • Related