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

Amir Shahabnia
Amir Shahabnia
29,310 Points

Extension practice (adding a number to a String type)

So the task here is to add an Integer to a String via Extension. I wrote this code (attached) and in Xcode I get the result of every String added by 2. However here on Treehouse the compiler says make sure to return Int?. However I'm pretty sure that Im returning Int?. If it's possible, would anybody help me out?

types.swift
// Enter your code below
extension String {
    var add: Int? {
        if let stringToInt = Int(self) {
            return stringToInt + 2
        } else {
            return nil
        }
    }
}

1 Answer

Amir, two issues. First, you need to add a function, not a variable. Second, you need to add whatever number is passed to the function, not just 2. 2 was an example. So it would look like this:

extension String {
    func add(i: Int) -> Int? {  //need a function - here I've named it add()
        if let stringToInt = Int(self) {
            return stringToInt + i  //need to return the converted String + the int passed in: i
        } else {
            return nil
        }
    }
}
Amir Shahabnia
Amir Shahabnia
29,310 Points

Thanks a lot, that helped a lot, yeah I totally forgot that we need a function here.