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

Chris Cynn
Chris Cynn
9,039 Points

Completing Intermediate Swift 3 Extension Challenge

Hi,

I have the below code written and the error I am encountering states I need to add an "add" method that takes and "Int" and returns "Int?", both of which I think I have? The prompt is below:

Your task is to extend the String type and add a method that lets you add an integer value to the string. For example: "1".add(value: 2) If the operation is possible, return an integer value. If the string does not contain an integer and you cannot add to it then return nil.

Thank you.

types.swift
// Enter your code below

extension String {
func add(number: Int) -> Int? {
guard let conNumber = Int(self) else {
return nil}
return conNumber + number
}
}

1 Answer

Aniruddha Shukla
Aniruddha Shukla
2,846 Points

The code snippet you have posted is correct. Strangely I just changed your parameter name in your add function from ' number' to 'value' and it worked.

func add(value: Int) -> Int? {
    guard let stringValue = Int(self) else {
        return nil
    }
    return stringValue + value
}

}