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

Haitham Alam
Haitham Alam
2,685 Points

Help with the challenge plz

Can i know what's wrong with my code??

types.swift
// Enter your code below
extension String {

    func add() -> Int? {

        let number: Int

    if number == Int(self) -> Int {

    return self

    } else {
    return nil
    }

    }

}

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Haytham Alam,

What we need to do here is create a method called "add" as an extension to the String type. This method will take an Int as its only parameter (to be added to the String when possible) and return an optional Int? based on whether the operation is possible.

Inside the body of this method, I use a guard statement to make sure that our String can be converted to an Integer. In cases where the conversion is not successful, we will return nil.

If the conversion from String to Int is successful, we will return the Int value of the converted string + the number we passed in when calling this method.

// Enter your code below

extension String {
  func add(n: Int) -> Int? {
    guard let conversion = Int(self) else {
        return nil
    }

    return conversion + n
  }
}

Hope this helps. Good Luck!