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

Kenan Bateman
Kenan Bateman
16,715 Points

String Extension Challenge

For this challenge, I'm not sure why this is not compiling and what the answer would be. I attached my code below.

Confused since if I take things out of the function they work.

This returns the integer 5....but when it goes inside a function, the compiler starts looking for it to be unwrapped.....no clue what I'm not noticing. Any help would be appreciated.

let textAsInt: Int? = Int("5")
types.swift
extension String {
    func add(value: Int) -> Int? {
        let textAsInt: Int? = Int(self)
        return textAsInt + value
    }
}

2 Answers

Jeff McDivitt
Jeff McDivitt
23,970 Points

Hi Kenan -

I completed the task using guard (see below)

extension String {

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

        return convertedNumber + value
    }

}

"1".add(value: 3)
Kenan Bateman
Kenan Bateman
16,715 Points

Thanks Jeff.....duh....not sure why I didn't think about the guard statement