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 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.
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)
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.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 do not store a value. Instead, they have getters and setters that retrieve and set values, respectively.
For example, look at the code below:
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)
Square
that has a computed property called area
.Square
with length=10
and then call the computed property to get the area.area
to update the length
of Square
accordingly.