Skip to content
DeveloperMemos

How to Use Computed Variables in Swift

Swift, Variables1 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.

Creating Computed Variables

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.0
3 var height = 0.0
4
5 var area: Double {
6 get {
7 return width * height
8 }
9 set(newArea) {
10 let ratio = newArea / area
11 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.

Using Computed Variables

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.0
3rectangle.height = 10.0
4
5print(rectangle.area) // Output: 50.0
6
7rectangle.area = 100.0
8print(rectangle.width) // Output: 7.0710678118654755
9print(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.

Conclusion

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.