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

Please help me pass this quiz

Your task is to extend the String type and add a method that lets you add an integer value to the string. For example: "1".add(2) If the operation is possible, return an integer value. If the string does not contain an integer and you cannot add to it, return nil.

They said "Bummer! Make sure you're adding method that takes an int and return int"

The challenge is to return nil if the string does not contain an integer. Am i missing anything here?

types.swift
// Enter your code below
extension String {
    func add(number: Int) -> Int! {
        guard let total: Int = Int(self)! + number else {
            return nil
        }
        return total
    }
}

1 Answer

Alexander Smith
Alexander Smith
10,476 Points

I made it like this...

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

instead of force unwrapping i used the ? marker so able to return the nil