Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Intermediate Swift 2 Properties Property Observers

David Murby
David Murby
4,700 Points

Error message: "Expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition"

In the code challenge I've created the didSet clause. Unfortunately I've now got an error message on the initialiser as given above. This gives me another message stating the class has no initialiser. Even when I copy the given code into a playground I get an error message on the super.init() line before I even add my code.

observer.swift
class TemperatureController: UIViewController {
    var temperature: Double {
        didSet {
            switch oldValue {
            case 80...1000: view.backgroundColor = UIColor.redColor()
            case 1..<40: view.backgroundColor = UIColor.blueColor()
            default: view.backgroundColor = UIColor.greenColor()
                }
            }


    init(temperature: Double) {
        self.temperature = temperature
        super.init()
    }

    override func viewDidLoad() {
        view.backgroundColor = UIColor.whiteColor()
    }
}

1 Answer

Good start. But there are 4 problems:

class TemperatureController: UIViewController {
    var temperature: Double {
        didSet {
            switch temperature {   //1 - you need to switch on temperature, not oldValue
            case 81...1000: view.backgroundColor = UIColor.redColor()  //2 - this case is "greater than 80", excluding 80
            case 0..<40: view.backgroundColor = UIColor.blueColor()  //3 - this case was "less than 40", including 0
            default: view.backgroundColor = UIColor.greenColor()
            }  // 4 - missing curly brace
        }
    }

    init(temperature: Double) {
        self.temperature = temperature
        super.init()
    }

    override func viewDidLoad() {
        view.backgroundColor = UIColor.whiteColor()
    }
}
David Murby
David Murby
4,700 Points

Superb, thanks jcorum. Fundamentally the problem was my switch being on oldValue so I appreciate the help. Valid points 2 & 3 so thanks for those too - 4 was a copy paste error! :) Curiously although the Treehouse system accepts the answer, Xcode (V7.3) still seems to have an issue with the super.init() statement. An issue for another day. Many thanks for helping out.