What are properties in programming?
Properties in programming are fundamental to understanding how structures and classes work. In the world of software engineering, particularly in languages like Swift, properties create the basis for storing and manipulating data. Often referred to as "Properties," due to their origin in the CTO world, these variables can be classified into different types.
What are stored properties?
Stored properties are variables or constants that are stored as part of a class instance or structure. They are known for their simplicity, being essentially elements that store direct values. These properties can be defined using var
for variables and let
for constants.
struct FixedLengthRange { var firstValue: Int let length: Int}
How are stored properties used in Swift?
To illustrate their use, let's consider a practical example. Let's imagine that we have a structure called FixedLengthRange
. Within this structure, we define both a variable(firstValue
) and a constant(length
). When creating an instance of the structure, we initialize these values:
var rangeOfItems = FixedLengthRange(firstValue: 0, length: 3).
After creation, we can modify the firstValue
variable since it is mutable:
rangeOfItems.firstValue = 6
However, we cannot change length
, since it was declared as a constant. Attempting to modify it would result in an error.
What common mistakes can we find with stored properties?
One of the most common errors when using stored properties occurs when trying to change the value of a property of an instance declared as a let
. Even if the property is a variable within the structure, the immutability of the instance prevents it.
let range = FixedLengthRange(firstValue: 0, length: 4)range.firstValue = 6
Swift helps to detect these typical errors by telling us that we must change let
to var
to allow the modification.
Where are stored properties used?
Stored properties are not only used in structures, but also in classes. Each variable or constant defined within a class or structure can be considered a stored property until other types of properties are explored.
For example, in classes, we have already explored a class called ViewModel
that had several stored properties to manage its state and functionalities.
In conclusion, stored properties are an essential element in object-oriented programming. Their correct definition and handling is fundamental to build efficient and error-free applications. As always, keep exploring and experimenting to deepen your knowledge!
Want to see more contributions, questions and answers from the community?