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 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.