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

Can anybody help with the "Extend a Native Type Challenge?" Here is my code:

extension String { func add(i: Int) -> Int? { if self.intValue { return self.intValue + i } else { return nil } } }

types.swift
// Enter your code below

extension String {
    func add(i: Int) -> Int? {
        if self.intValue {
            return self.intValue + i
        } else {
            return nil
        }
    }
}

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Nehemiah,

You're close, but there are two issues with your code:

  1. Swift Strings don't have a property intValue like NSStrings do.
  2. In Swift you can't use an if statement like that - you could say if thingThatMightBeNil != nil, but using guard or if let is better

Here's a solution using if let:

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

and here's one using guard, which I prefer in this case:

// Enter your code below
extension String {
    func add(i: Int) -> Int? {
        guard let numberFromString = Int(self) else {
            return nil
        }
        return numberFromString + i
    }
}

Let me know if any of this doesn't make sense!

Happy coding :thumbsup:

-Greg

Thanks! Makes perfect sense now. I was looking into the NSString documentation lol. I'm sort of a newbie at programming still polishing up.

Greg Kaleka
Greg Kaleka
39,021 Points

Awesome - glad I could help!