Computed Property in Swift

Object creation is a heavy process. When we create a class object, all the public and private properties of that class are initialised inside the constructor. Every variable inside a class initialisation requires a certain amount of time to allocate the memory on the heap and hold its reference on the stack. The more variables, the more time it may take but since the time is in microseconds or even less, it’s not observable.

Sometimes we don’t need all the objects to be initialised during the class object creation itself.
There can be two reasons for that.

  1. That object/property/variable is dependent on another object to initialise first and use its reference.
  2. The flow is such that we need that object only in a certain condition.

In Swift, we have certain features which can help us in delaying that object initialisation as per the requirement.

One way of doing that is using computed properties.
Computed properties are the properties that don’t get initialised while object creation or constructor is called. They get computed every time the property is accessed.
We can use it for any heavy computation which we want to do on a conditional basis. Unlike Lazy properties, these properties get computed every time the property is accessed.

The basic initialisation of a computed property in a User class object by will look like below

Please continue reading at https://agrawalsuneet.github.io/blogs/computed-property-in-swift/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store