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 Extensions and Protocols Protocol Extensions

philip williams
philip williams
5,991 Points

struggling with extensions a lot, can anyone help?

I don't understand whats going. Any help will be greatly appreciated.

protocols.swift
protocol Math {
  func square(value: Double) -> Double
}

// Enter your code below
extension Math {
  func squareValue() -> Double {
    return ("The square of \(value) is \(value * value)")
  }
}

Hint: your returning a Double in the function declaration but your returning a String in the implementation

2 Answers

Steven Deutsch
Steven Deutsch
21,046 Points

Hey philip williams,

Nehemiah Reese was kind enough to give you a hint, but let me see if I can help clear up your understanding of extensions for you.

An extension is just a way of adding additional functionality to a type. This could be a native Swift type, a type in one of the iOS Frameworks, or even a custom type of our own.

In Swift, protocol's are first class citizens. They are fully fledged types of their own. This means we can use an extension on them like we would any other type.

If you recall, protocols are blueprints in a sense - blueprints of what properties and methods our data types will contain. They are not an actual implementation of these properties and methods. They just define what they will look like.

In order for a data type to conform to a protocol, it has to implement all the properties and methods that are defined in that protocol. This also means that we have to use the same naming conventions for the method names, computed property names, and the methods need to have to same function signatures.

So what we want to do here is extend the Math protocol and give it an actual implementation instead of previously just having the blueprint defined in the original protocol.

protocol Math {
  func square(value: Double) -> Double
}

// Enter your code below
// Take note how my implementation of this method matches the one defined in the protocol
// Same name, parameter names, and signature
// The only thing new here is we are adding the function body
extension Math {
  func square(value: Double) -> Double {
    return  value * value
  }
}

Good Luck

philip williams
philip williams
5,991 Points

Thanks Steven and Nehemiah. Really appreciate the help.