Computed Property in Swift

Suneet Agrawal
2 min readDec 3, 2021

--

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.

This post was originally posted at https://agrawalsuneet.github.io/blogs/computed-property-in-swift/ and reposted on Medium on 03rd Dec 2021.

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

struct User {
let name : String
let age : Int
}
struct Department {
var users : [User]

init(users : [User]) {
print("Department constructor is called")
self.users = users
}

var youngestUser : User? {
print("Department youngestUser is computed")
return self.users.min(by: {$0.age < $1.age})
}
}

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.

--

--