Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What do you call this kind of parameter and is it thread safe?

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading