Computed properties

Stored properties are certainly the most common, but there are also properties that are computed, which simply means they perform a calculation before returning a value.

While a stored property can be a constant or a variable, a computed property must be defined as a variable. Computed properties must also include a type, because the compiler needs to know what to expect as a return value.

The measurement for a TV is the perfect use case for a computed property. The industry definition of the screen size of a TV isn’t the screen’s height or width, but its diagonal measurement:

struct TV {

var height: Double var width: Double

// 1

var diagonal: Int {

// 2

let result = sqrt(height height + width width)

// 3

let roundedResult = result.rounded()

// 4

return Int(roundedResult)

}

}

Let’s go through this code one step at a time:

  1. You use an Int type for your diagonal property. Although height and width are each a Double, TV sizes are usually advertised as nice, round numbers such as 50" rather than 49.52". Instead of the usual assignment operator = to assign a value as you would for a stored property, you use curly braces to enclose your computed property’s calculation.
  2. As you’ve seen before in this book, geometry can be handy; once you have the width and height, you can use the Pythagorean theorem to calculate the width of the diagonal.
  3. If you convert a Double directly to Int, it truncates the decimal, so 109.99 will become just 109. That just won’t do! Instead, you use the rounded(_:) method to round the value with the standard rule: If it the decimal is 0.5 or above, it rounds up; otherwise it rounds down.
  4. Now that you’ve got a properly rounded number, you return it as an Int.

Computed properties don’t store any values; they simply return values based on calculations. From outside of the structure, a computed property can be accessed just like a stored property. Test this with the TV size calculation:

var tv = TV(height: 53.93, width: 95.87) let size = tv.diagonal // 110

You have a 110-inch TV. Let’s say you decide you don’t like the standard movie aspect ratio and would instead prefer a square screen. You cut off some of the screen width to make it equivalent to the height:

tv.width = tv.height

let diagonal = tv.diagonal // 76

Now you only have a 76-inch square screen. The computed property automatically provides the new value based on the new width.

results matching ""

    No results matching ""