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

Bruce Röttgers
Bruce Röttgers
18,211 Points

Stuck in Challenge 1, what is false with the method?

I'm trying to solve that, but I don't understand how I can give an external argument as an underscore.

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 {
  let state: LightState
  var color: Color

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

1 Answer

Royce Pollard
Royce Pollard
24,267 Points

Hello,

Your in the right direction!

To omit the external name you do use an underscore. For example:

func someFunction(external local: String) {}

Where the "external" is what will show when you can the fund and initialize it. When you call it it looks like this:

someFunciton(external: String)

to omit it you use the underscore; someFunction(_ local: String)

Then it will show: someFunction( )

The "local" is the name you use in the fund when you are creating the body of the method. But in the code it looks like

someFunction(external local: String) { return "This is (local)'s function." }

protocol ColorSwitchable { func switchColor( _ color: Color) }

Bruce Röttgers
Bruce Röttgers
18,211 Points

Already tried that but it gives me a compiler error

Royce Pollard
Royce Pollard
24,267 Points

Ok I see the problem. Trying using the underscore again.

This time remember in protocols they are more like guidelines to ensure certain objects adhere to certain structuring. They do not have to be implemented in the protocol. Only when you create the object that adheres to the protocol will you have to create an implementation for the protocols restrictions.

for example:

protocol SomeName { func getNames(_ names: Array) }

// You're are just saying an object has to implement this func somehow. Meaning No parentheses

But not:

protocol SomeName { func getNames(_ names: Array) { // You do not need to provide implementation in the protocol itself. } }

Short and sweet: You do not need the parentheses at the end of your method in the protocol.