What is the computed property in swift and how to use it ?

Hello everyone. Today we are gonna look at the computed property in swift and use it within a small example. So what is computed property ?

It is a property that you can make some calculations during setting it’s value.  The value of the computed property is usually computed when you request it. We can think of it as a function disguised as a property. Let’s make an example to understand it properly.

We are going to create a swift file called cars.swift . The content will be like that :

import Foundation
 
struct Car {
    var modelName = ""
    var modelYear = 0
    let currentYear = Calendar.current.component(.year, from: Date())
    var Age : Int {
        get {
            return (currentYear - self.modelYear)
        }
        set(carAge){
            self.modelYear = (currentYear - carAge)
        }
    }
}

In this structure we can calculate the car’s age value by using its model year and current year. Also when we set the Age value, it will change the car’s model year.

Now let’s call this Car struct within the main.swift file. :

import Foundation
 
var myCar = Car(modelName:"Porsche",modelYear : 2017)
print(myCar.Age)

When you run the main.swift file then the output will show the car’s age according to the modelYear. Here, if I change the myCar.Age value then the myCar.modelYear will be calculated automatically.

import Foundation
 
var myCar = Car(modelName:"Porsche",modelYear : 2017)
print(myCar.Age)
myCar.Age = 2
print(myCar.modelYear)

If I run the main.swift file again, the myCar.modelYear will be changed from 2017 to 2020. (We are in 2022 right now.) 

So that’s it. It was a short post but it is still useful.

You may also like...