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!

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 Conformance Through Extensions

Habib Miranda
Habib Miranda
7,320 Points

I am stuck here. I feel like I'm over thinking this...

can someone help?

protocols.swift
protocol PrettyPrintable {
    var prettyDescription: String { get }
}

struct User {
    let name: String
    let ID: Int
}

// Enter your code below

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Habib Miranda,

Don't over think things! This one is quite simple. As you know for a data type to conform to a protocol, it has to implement all the required methods and properties of that protocol. Normally, you would just conform to the protocol by adding these methods or properties to the definition of the data type directly, however, in this situation we will achieve the conformance by extending the User type.

All you have to do is create an extension of the User struct and list the protocol that it inherits from just as you would do normally and the same way how you would specify a parent class of a subclass.

Then inside the body of that extension is where you write the actual implementation of the requirements defined in the PrettyPrintable protocol. In this case, there is only a single requirement:

We have to create a computed property (read only) that returns a String. The property must be named prettyDescription. The string we return here doesn't matter for the challenge to pass. The purpose was just to achieve protocol conformance.

protocol PrettyPrintable {
    var prettyDescription: String { get }
}

struct User {
    let name: String
    let ID: Int
}

// Enter your code below

extension User: PrettyPrintable {
  var prettyDescription: String {
    return "This string does not matter for the challenge"
  }
}

Good Luck!