Learn

There is another way we can access private properties inside of a structure: computed properties. Computed properties are a special type of property that don’t actually store a value directly, rather use other properties and constants to compute and return a value.

Syntactically, computed properties look more like methods than properties. We define a getter and optionally, a setter, for each computed property. A getter, denoted by the get keyword, is used to retrieve the value of a property. A setter, denoted by the set keyword, is used to set the value of a property. We’ll cover setters more in-depth in the following exercise.

As you might suspect, the getter defines the value to return when we read the property. A computed property with only a getter is known as a read-only computed property. Here is an example of a read-only computed property:

struct Cat { private var numberOfLives: Int var doubledLife: Int { get { return numberOfLives * 2 } }
  • We declare doubledLife as an Int type.
  • The brackets after the type give us a scope for the getter.
  • The get keyword defines the getter.
  • The return keyword ends the scope of the getter and returns a final value.

A read-only computed property can be handy in cases where you want to safely give read access to some property but want to be sure it can’t be modified. It should be noted that in the preceding example we are accessing a private property, but computed properties aren’t limited to private properties and can include properties of any access control level. We should also note that computed properties don’t have type inference; we must explicitly define their type.

Instructions

1.

Make a read-only computed property named totalRevenue of type Int that returns the product of ( paperclipCost and paperclipSales ) added to getSecretRevenue().

2.

Delete the line that defines totalRevenue in the printTotalRevenue() so that it uses the new computed variable.

3.

Now use dot syntax to get the totalRevenue computed property from the alphaOffice instance, and print its value to the console.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?