Hidden feature: static properties
You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿
I want to show you a nice hidden feature of static
properties!
So let’s have a look at an example!
This is a typical use case of a static
property: storing a value that will be shared across all instances of a type.
And if you’ve used statics a lot, you might have wondered whether they had an impact on the launch time of your app?
After all, these static
values must be initialized at one point or another. 🤨
And if you add up all the code needed to initialize them, it would take a bit of time, wouldn’t you think?
And that’s when this hidden feature of statics comes into play!
To see this hidden feature in action, let’s add a print()
statement in the initialization closure of the static
:
And now if you start your app using this updated code, you’ll see in the console that the print()
isn’t executed.
To be more precise, the print()
won’t be executed until you reach the first line of code that actually uses the static
property.
And that’s because in Swift, static
properties are also implicitly lazy
, which means that they don’t get initialized until they’re actually used!
Another way to highlight this hidden feature is to explicitly declare the static
property as lazy
: you’ll then get an error message informing you that the static
property is already lazy
.
This hidden feature is a pretty good news because it means that even if you have lots of static
properties in your app, they won’t be initialized all at once when you app launches 😌
That’s all for this article, I hope you’ve enjoyed this new format!
Here’s the code if you want to experiment with it:
import Foundation
class EventsViewModel {
static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter
}()
// ...
}