Read-only properties in Swift
What is a read-only property? How do you create one in Swift programming language?
Read-only means that we can access the value of a property but we can’t assign any value to it.
Often developers confuse Read-only with Constants when we ask them for the definition!
What is expected of a Read-Only property?
Let us imagine a class called Addition like the one below
class Addition {
var lhs: Int = 0
var rhs: Int = 0
var sum: Int = 0
}
When you try to print the property “sum” from an instance of this class, the console should always print the sum of values of “lhs” and “rhs”. After printing sum once and then if we change the value of either “lhs” or “rhs” or both and print the value of “sum” again, it should print the updated sum of “lhs” and “rhs”.
Later if we try to assign a value to “sum” like
var obj = Addition()
obj.lhs = 10
obj.rhs = 20
print(obj.sum)obj.sum = 50 // compiler error here
print(obj.sum)
This will result in a compiler error.
Creating a read-only property
Read-only properties are also known as Computed Properties in Swift. Most of the programming languages including Swift has the concept of “Getters & Setters”.
Any normal variable you create in Swift will by default has a getter & setter created for it. since this happens internally we don't have to worry about it. Sometimes the developer would want to take matters to hand and define a custom getter & setter for their variables.
var myValue: Int {
get {
return 10
}
set {
save(newValue)
}
}
In swift, we can create a read-only property by only defining a getter for a variable. Meaning no setter!
var sum: Int {
get {
return lhs + rhs
}
}
Since the variable only has a getter, the compiler will throw an error when we try to assign a value to “sum”.
With the new updates in Swift you can even reduce the number of lines you type like this:
var sum: Int {
lhs + rhs
}
Question time!
Try and create a read-only property in Objective C. If you have an answer post a response!
Bonus!
What is a constant?
A constant is a value that should not be altered by the program during normal execution.
In swift, we can create a constant value by using the “let” keyword. For example:
let aConstant = 10
About me
Check: https://about.me/chandrachudhk
Here’s a donut for you!
Read-only properties in Swift was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.