Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Intermediate Swift Extensions and Protocols Extending a Native Type

Richard Pitts
Richard Pitts
Courses Plus Student 1,243 Points

What is the correct answer?

I have no clue, but am looking for the correct answer and maybe a little explanation relative to my attempt. Thanks.

// Enter your code below

extension String { add(value: Int) } -> Bool return Int?

1 Answer

David Papandrew
David Papandrew
8,386 Points

Hi Richard,

You need to create a new method called "add". The method may or may not return an Int. So you are headed in the right direction with your solution above.

In the body of the method, you want to check if a string ("self") calling the add method can be recast as an Integer or not. So you'll use an if statement to do this.

Here's the code:

extension String {
    func add(value: Int) -> Int? {
        if Int(self) != nil {
            return Int(self)! + value
        } else {
            return nil

And to use the extension:

"2".add(value: 10)  // <== returns 12
"Dog".add(value: 10)   // <== returns nil