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

Edwin Carrasquillo
Edwin Carrasquillo
10,315 Points

A question on extending a type while typecasting to another type

I think I could probably complete this using a function instead of a computed property, but I think the challenge expects a computed property. The issue being as seen by my code, the compiler is telling me I need to unwrap the variables while unwrapping the variables, but if I try and do that it complains that I'm using undeclared variables.

I'm stuck on this one and any help would be appreciated!

types.swift
extension String {
    var add: Int? {
      guard let totalNumber = Int(self) + add else {
        return nil 
        }
    }
}

1 Answer

David Papandrew
David Papandrew
8,386 Points

Hmm...I haven't done this module yet, but from looking at the question it does state that it wants you to write a new method (i.e. function).

If that's the case, this solution will work (I submitted it and it passed):

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

And to invoke the new string method:

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