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

Luigi Santos
Luigi Santos
13,200 Points

does anybody have the working code to this quiz? I've tried everything, and also using fahrenheit = newValue

what else do you need to add to the setter method?

Temperature.swift
class Temperature {
    var celsius: Float = 0.0

    var fahrenheit : Float {
      get {
        return (celsius * 1.8) + 32
      }
      set {
        fahrenheit = newValue
        celsius = (fahrenheit - 32) / 1.8
      }
    }
}

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

I don't know the proper terms to explain it, but in your setter method, when you try and set 'fahrenheit' with 'newValue' it gets confused because it thinks your referring to the fahrenheit property, not some temporary variable, but the fahrenheit property is the computed property that you're in the process of defining the setter method on. So it gets weird.

I fixed it by just removing that line of code and using newValue in the place of fahrenheit on the next line:

class Temperature {
    var celsius: Float = 0.0

    var fahrenheit : Float {
      get {
        return (celsius * 1.8) + 32
      }
      set {
        celsius = (newValue - 32) / 1.8
      }
    }
}
Luigi Santos
Luigi Santos
13,200 Points

that makes so much sense. thank you Brendan!

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

Just out of curiosity, I put your code into an Xcode playground. It didn't give an error it just gave a warning - but the warning said "Attempting to modify fahrenheit with its own setter".

Luigi Santos
Luigi Santos
13,200 Points

yeah, that's what I did as well. that's why it didn't make sense to me and I wasn't sure where I went wrong.