Learn

In addition to getting computed properties, there may be cases where it would be convenient to set the computed property as well. Recall that computed properties don’t store values directly, so we’ll actually be setting the underlying stored properties that our computed property is derived from.

Going back to our feline structure, we have our computed property, doubledLife:

struct Cat { private var numberOfLives : Int var doubledLife : Int { get { return numberOfLives * 2 } } }

The easiest way to create the setter is to treat the getter as an algebraic equation:

doubledLife = numberOfLives * 2

Now we solve for numberOfLives by dividing both sides by two:

numberOfLives = doubledLife / 2

We can complete the syntax for the setter using the set keyword, which also passes in the new value of the computed property. We can name this value anything, so let’s call it newDoubledLife for clarity:

struct Cat { private var numberOfLives : Int var doubledLife : Int { get { return numberOfLives * 2 } set(newDoubledLife) { numberOfLives = newDoubledLife / 2 } } }
  • The set keyword begins our setter definition
  • The newDoubledLife parameter passes in the new value that we are assigning to doubledLife .
  • We set the underlying stored property numberOfLives which doubledLife is derived from.

There are a few shorthand forms of computed properties you can use to make your code more concise and readable. The first one you should know is that read-only computed properties can omit the get keyword:

var doubledLife : Int { numberOfLives * 2 }

The second is that computed properties with a getter and setter can omit the return if the entire body of the getter is a single expression:

var doubledLife : Int { get { numberOfLives * 2 } set(newDoubledLife) { numberOfLives = newDoubledLife / 2 } }

Finally, we can omit the passed parameter on the setter and use the default newValue that is provided to us:

var doubledLife : Int { get { numberOfLives * 2 } set { numberOfLives = newValue / 2 } }

To recap: in order to set a computed property, we need to set all of the stored properties it’s derived from. We solve algebraically for the stored properties in terms of the computed property. Lastly, we learned about the shorthand forms we can utilize to make our code more concise.

Instructions

1.

Add a setter to the totalRevenue computed property. Name the value that the setter passes in: newTotalRevenue.

2.

In the body of the setter, reassign paperclipSales to be equal to the difference of the newTotalRevenue and the secret revenue, divided by the paperclipCost.

3.

Use the dot syntax on the alphaOffice instance to set totalRevenue to 400, and observe the new total revenue in the terminal.

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?