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 trialGene Bogdanovich
14,618 PointsProperty Observers Code Challenge in Intermediate Swift 3
I have no idea how to make it work. Please help!
class TemperatureController: UIViewController {
var temperature: Double {
didSet(newValue) {
if newValue > 80.0 {
super.viewDidLoad()
view.backgroundColor = UIColor.red
} else if newValue < 40.0 {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
} else {
super.viewDidLoad()
view.backgroundColor = UIColor.green
}
}
}
init(temperature: Double) {
self.temperature = temperature
super.init()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
}
1 Answer
Dan Lindsay
39,611 PointsHey Eugene,
It looks like you are making it more complicated than it has to be. We don't have to worry about creating a newValue variable here, and super.viewDidLoad() only needs to be called once inside the viewDidLoad() method. Use temperature as the value you are comparing if greater than or less than, and you should pass the challenge. This worked for me:
class TemperatureController: UIViewController {
var temperature: Double {
didSet {
if temperature > 80.0 {
view.backgroundColor = UIColor.red
} else if temperature < 40 {
view.backgroundColor = UIColor.blue
} else {
view.backgroundColor = UIColor.green
}
}
}
init(temperature: Double) {
self.temperature = temperature
super.init()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
}
Hope this helps!
Dan
Gene Bogdanovich
14,618 PointsThank you very much, Dan!
Cameron Hyatt
5,948 PointsI tried using a switch inside the didSet for mine but it was giving me errors about Bool and Double types. Maybe I'm forgetting something because I've been away too long but wouldn't the switch statement work instead of an if-else statement?
akyya mayberry
3,668 Pointsakyya mayberry
3,668 PointsAlso to note, I think if you specify a named argument for didSet as you did 'newValue' it actually holds the previous value (the old value) of temperature not the current temp. didSet is triggered when a change is done to temperature. didSet has the old value (oldValue or in your code newValue) and access to the new value (temperature). This is from Swift docs,