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 Properties Getter and Setter Methods

Terrez dawson-holland
Terrez dawson-holland
1,656 Points

Whats wrong with my code?

Im stuck on getter and setter methods 2 stage 3 properties

It wants me to input a getter and setter method..

"When the user assigns a value to the fahrenheit property, the setter method will calculate and assign a value to the celsius property. (Note: Celsius = (Fahrenheit-32)/1.8))"

Temperature.swift
class Temperature {
    var celsius: Float = 0.0
    var Fahrenheit: Float {
       get { return (celsius * 1.8) + 32.0 }
       set { celsius = (Fahrenheit-32)/1.8 }

    }    
}
Jeanne Merle
Jeanne Merle
3,390 Points

in my "get" method, I wrote :

get { return self.fahrenheit }

why do i have to re-define the result with celsius althought fahrenheit has its own value ?

thx

nec
nec
3,886 Points

I don't fully understand your question. Are you asking why you have to redefine Fahrenheit within the "set" method? Or elsewhere?

Jeanne Merle
Jeanne Merle
3,390 Points

in fact, I just wanted to return the value (in the "get method") without using a conversion. I just wanted to return "self.fahrenheit" but it wasn't good ...

nec
nec
3,886 Points

I don't believe you can use self.fahrenheit inside the get method because it is a function of the variable fahrenheit. What is inside the curly brackets are used to compute the value of fahrenheit. The value of fahrenheit does not yet exist.

This is different from using the self.fahrenheit in an init method for example where you are telling the computer that whatever value is stored in fahrenheit should be used as the initial value.

This is my understanding of it from the courses in the Swift Track.

1 Answer

nec
nec
3,886 Points

I think you need to use newValue in place of Fahrenheit in your setter method.

nec
nec
3,886 Points

Fahrenheit is a computed property which does not have a stored value so you need to use the newValue cause you can't call it directly in the setter method.

I don't have had much experience using the getter and setter method yet so I can't give a more in depth answer. Perhaps more experienced developer can chime in.