What are the stored and computed properties of a Swift class?

In Swift, properties are the values associated with a structure or a class instance. Stored and computed properties are the two different types of properties.

Stored properties

Stored properties are the values (constants or variables) stored in a class/structure instance. We can set a default value for a stored property, which can be modified later.

However, the value can only be modified in the case of variables. If we try to modify a stored property or class instance created using the let keyword, we'll get an error.

Code

struct Grade {
var marks: Int // variable
let subject: String // constant
}
// variable class instance
var mathsGrade = Grade(marks: 50, subject: "Maths")
mathsGrade.marks = 90
// the following line will throw an error
// mathsGrade.subject = "Mathematics"
print(mathsGrade)
// constant class instance
let englishGrade = Grade(marks: 100, subject: "English")
// the following line will throw an error
// englishGrade.marks = 80
print(englishGrade)

Explanation

  • Lines 7–11: We initialize an instance of Grade using the var keyword. We also update the value of the stored property marks and then display that instance. We have commented out Line 10 because subject is a constant stored property and trying to modify that will result in an error.
  • Lines 14–17: We initialize another instance Grade with different parameters using the let keyword. We have commented out line 16 because running it will throw an error since englishGrade is a constant instance.

Computed properties

Computed properties do not store a value. Instead, they have getters and setters that retrieve and set values, respectively.

For example, look at the code below:

Code

struct Square {
var length: Double
var area: Double {
get {
return length * length
}
set(newArea) {
length = sqrt(newArea)
}
}
}
var mySquare = Square(length: 10)
print("The are of the square is:", mySquare.area)
mySquare.area = 25
print("The length of the updated square is:", mySquare.length)

Explanation

  • Lines 1–11: We define a structure Square that has a computed property called area.
  • Lines 13–14: We initialize a Square with length=10 and then call the computed property to get the area.
  • Lines 16–17: We call the setter of the computed property area to update the length of Square accordingly.

Copyright ©2024 Educative, Inc. All rights reserved