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 Extensions and Protocols Extending a Native Type

Richard Pitts
PLUS
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.

types.swift
// 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