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 Properties Property Observers

Lorenzo Leva
Lorenzo Leva
12,262 Points

Switch case?

Hi, wondered why my code doesn't work with a switch case but only with an if-else clause. In theory, it should work. Thank you already for your help. Here is my code:

observer.swift
class TemperatureController: UIViewController {
    var temperature: Double {
      didSet {
        switch self {
          case let x where x > 40 : view.backgroundColor = .blue
          case let x where x < 80 : view.backgroundColor = .red
          default: view.backgroundColor = .green
        }
      }

    }

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

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }
}

1 Answer

Hi there,

Your errors are:

swift_lint.swift:73:30: error: binary operator '>' cannot be applied to operands of type 'TemperatureController' and 'Int'
          case let x where x > 40 : view.backgroundColor = .blue
                           ~ ^ ~~

swift_lint.swift:74:30: error: binary operator '<' cannot be applied to operands of type 'TemperatureController' and 'Int'
          case let x where x < 80 : view.backgroundColor = .red
                           ~ ^ ~~

So, you're comparing the wrong thing by just using self - that refers to the controller, not the member variable. Use self.temperature for your switch.

Then, check your logic. You are testing for greater than 40 and less than 80. That's not what the question is looking for.

    var temperature: Double {
      didSet {
        switch self.temperature {
          case let x where x < 40 : view.backgroundColor = .blue
          case let x where x > 80 : view.backgroundColor = .red
          default: view.backgroundColor = .green
        }
      }
    }

Steve.