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 // variablelet subject: String // constant}// variable class instancevar mathsGrade = Grade(marks: 50, subject: "Maths")mathsGrade.marks = 90// the following line will throw an error// mathsGrade.subject = "Mathematics"print(mathsGrade)// constant class instancelet englishGrade = Grade(marks: 100, subject: "English")// the following line will throw an error// englishGrade.marks = 80print(englishGrade)
Explanation
- Lines 7–11: We initialize an instance of
Gradeusing thevarkeyword. We also update the value of the stored propertymarksand then display that instance. We have commented out Line 10 becausesubjectis a constant stored property and trying to modify that will result in an error. - Lines 14–17: We initialize another instance
Gradewith different parameters using theletkeyword. We have commented out line 16 because running it will throw an error sinceenglishGradeis 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: Doublevar 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 = 25print("The length of the updated square is:", mySquare.length)
Explanation
- Lines 1–11: We define a structure
Squarethat has a computed property calledarea. - Lines 13–14: We initialize a
Squarewithlength=10and then call the computed property to get the area. - Lines 16–17: We call the setter of the computed property
areato update thelengthofSquareaccordingly.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved