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 trialMazen Halawi
7,806 PointsUnderstanding the setter method in a property?
I am quite ok with the getter method, and i know that the setter method is actually used to set other properties (or maybe im wrong here) using the newValue, but those values dont change or am i doing it wrong. please check the below example:
var length: Int?
var width: Int?
var area: Int {
get {
if let w = width, let l = length {
return w * l;
} else {
return 0;
}
}
set {
length = newValue / 2;
width = newValue / 2;
}
}
length = 4 // returns 4
width = 8 // returns 8
area // returns 32
length // still returns 4
width // still returns 8
I dont understand the use of the setter here or anywhere else.
1 Answer
Florin Veja
6,912 PointsMazen,
You got it. You have to set area, for the setter to get called.
Mazen Halawi
7,806 PointsMazen Halawi
7,806 PointsI understood it now. the set method runs when you assign a value to the area. so if i was to say area = 16 then that will set the length and width to ( 16 / 2 = 8)