Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Object-Oriented Swift Complex Data Structures Methods

Kanish Chhabra
Kanish Chhabra
2,151 Points

What are getter and setter properties?

I need an explanation of getter and setter properties with and example, I read about on Apple's website which was linked in the teacher's notes but they've not used simple language so I was not able to understand it. Please help :)

Lukas G.
Lukas G.
4,842 Points

Hello Kanish, I hope I can clean things up. I think you are talking about calculated values here. 1) getter - getter is what you... well, get when you access a property. Example:

var someProperty = 4
var calculatedProperty: Int {
   get {
      return someProperty * 2
   }
}

let answer = calculatedProperty

In this case you get 8 back. 2) setter - the name setter could be a little misleading, since you don't set calculated values. What is does is, it sets other values when the calculatedProperty is calculated.

var someProperty = 4
var anotherProperty = 0

var calculatedProperty: Int {
   get {
      return someProperty * 2
   }
   set {
      anotherProperty = newValue / 4
   }
}

Now, when you calculate "anotherProperty" will also be set. You can access the newly calculated value with "newValue". You can also explicitly give it a name by:

set (myCustomName) {
   print(myCustomName)
}