iOS Interview: Computed Property

Ravi Ranjan
CodeX
Published in
3 min readSep 28, 2022

Before Jumping into Computed property first let’s understand what is Property.

Properties are values associated with a class, struct, or enumeration type in Swift. An example of this is for a Car we have Wheels, Doors, HeadLight, Steering, etc are the properties by which we can build a car. these properties can be constant or can vary in nature depending upon the part of the instance. eg. A car can have 2 or 4 doors so it is a variable but a car can have only one steering so it is constant in nature.

Below is the bone structure for a car yes we can have other properties as well but for the sake of simpleness, I just took these five of them.

Computed properties are the property that does not store the value rather than calculate the value. so as the computed property does not store a value it provides a getter to retrieve an optional setter to set other properties and values indirectly.

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.

let’s understand with this an example of our car class.

let’s suppose we want to access the beam length of the headlight and we have a simple formula:
beamLength = numberOfLights * 10

so what we can do is we can have a function that can calculate the beam length.

Now this is a very simple calculation and it does not require any parameter, and no validation is required also it will not throw any kind of error so instead of creating a function we can create a computed property.

A computed property is effectively just a function call that happens to belong to your struct mean Computed property is similar to a normal function which will return a value of certain type but it can’t accept parameters.

this computed property will act similar to the function we have written but is so concise. and to validate more if you have created a computed property with some name you can’t create a function with the same name unless you modify the parameters.

Please find great article below for computed property :

If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. If you have any queries or suggestions, feel free to comment or hit me on Twitter, or Linkedin.

--

--