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 Protocols in Swift Protocol Basics Protocols With Methods

Chase Maddox
PLUS
Chase Maddox
Courses Plus Student 5,461 Points

Protocols: Changing Variables Inside a Function

Hi,

I'm not sure how to change the color to the new color. What am I not doing properly?

Thanks, Chase

protocols.swift
// Declare protocol here
protocol ColorSwitchable {
  func switchColor(_ color: Color)
}

enum LightState {
  case on, off
}

enum Color {
  case rgb(Double, Double, Double, Double)
  case hsb(Double, Double, Double, Double)
}

class WifiLamp: ColorSwitchable {
  let state: LightState
  var color: Color
  func switchColor(_ color: Color) {
    var color = color
  }

  init() {
    self.state = .on
    self.color = .rgb(0,0,0,0)
  }
}

1 Answer

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

Almost there!

In the body of your switchColor implementation, however, you are not assigning the passed in color to the color property of WifiLamp.

func switchColor(_ color: Color) {
   // This would be a new variable named color, not addressing the WifiLamp color property. 
   // Moreover color is already the parameter name
   var color = color
}

What you really want to do is

func switchColor(_ color: Color) {
   self.color = color
}

Please note that self.color is necessary to let the compiler know that you want to assign to the colorproperty of the class. Otherwise it would be ambiguous. Other languages use this to indicate that.

If your parameter name and the property name did not match, you could do it like this:

func switchColor(_ myColor: Color) {
   color = myColor
}

Hope that helps :)