— Swift, Variables — 1 min read
In Swift, computed variables allow developers to define a property that doesn't actually store a value, but instead provides a getter and/or setter method to calculate and return a value based on other properties or methods. This is particularly useful for performing calculations or returning dynamic data based on other data.
To create a computed variable in Swift, you can use the get
and/or set
keywords along with curly braces { }
to define the getter and/or setter method(s). For example:
1class Rectangle {2 var width = 0.03 var height = 0.04 5 var area: Double {6 get {7 return width * height8 }9 set(newArea) {10 let ratio = newArea / area11 width *= sqrt(ratio)12 height *= sqrt(ratio)13 }14 }15}
In this example, the Rectangle
class defines a computed variable area
that calculates and returns the area of the rectangle based on its width
and height
properties. The get
method defines how to calculate and return the area, while the set
method allows the area to be set and adjusts the width
and height
properties accordingly to maintain the same aspect ratio.
Once a computed variable is defined, it can be used just like any other property. However, since it doesn't actually store a value, it must be calculated each time it is accessed. For example:
1let rectangle = Rectangle()2rectangle.width = 5.03rectangle.height = 10.04
5print(rectangle.area) // Output: 50.06
7rectangle.area = 100.08print(rectangle.width) // Output: 7.07106781186547559print(rectangle.height) // Output: 14.142135623730951
In this example, we create a new Rectangle
object and set its width
and height
properties. We then access the area
computed variable, which calculates and returns the area of the rectangle (50.0
). We then set the area
property to a new value (100.0
), which adjusts the width
and height
properties based on the current aspect ratio of the rectangle.
Computed variables are a powerful feature in Swift that allow developers to define properties that don't actually store a value, but instead compute and return a value based on other data. This can be useful for performing calculations, returning dynamic data, and maintaining data integrity.