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

Matthew Ingram
PLUS
Matthew Ingram
Courses Plus Student 4,718 Points

Adding Extensions trouble with treehouse's compiler

When I use the code in playground it works fine but in, I get an error message when I check my work!

types.swift
// Enter your code below



extension String{
    var Add : Int? {
        if Int(self) != nil {
            return Int(self)! + 1
        } else {
            return nil
        }
    }
}

5 Answers

Jeff McDivitt
Jeff McDivitt
23,970 Points

Hi Matthew -

Yes it will work, but the treehouse challenges are very specific and that is why it does not work in there

Jeff McDivitt
Jeff McDivitt
23,970 Points

Hi Matthew -

  1. You first need to create a method that lets you add an integer value (I do not see this in your code)
  2. I use a guard statement to check if the string contains an integer value and if not it returns nil
  3. If it does contain and integer then it returns the converted number plus the value
extension String {

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

        return convertedNumber + value
    }
}
Matthew Ingram
PLUS
Matthew Ingram
Courses Plus Student 4,718 Points

extension String{

func add(number: Int) -> Int?{

    if Int(self) != nil {
        return Int(self)! + number
    } else {
        return nil
}
    }
}
Jeff McDivitt
Jeff McDivitt
23,970 Points

No this will not work I provided the correct way to do it in my last response. Are you just looking for other ways to achieve the result?

Matthew Ingram
Matthew Ingram
Courses Plus Student 4,718 Points

yes thank you for your response I wrote the code above in Playground and it seemed to work without any problem but within the treehouse compiler, it was denied. Is the main issue that I forced unwrapped it?