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 trialTodd Stacy
5,816 Pointshow do extensions work exactly?
okay the video was no help to me at all on this one. i really dont know how to go about this. i understood when he extended an int to a bool, but this is just flying over my head.
// Enter your code below
extension String {
var add: Int {
if self == add{
return self + "\(add)"
} else {
return nil
}
}
}
1 Answer
Steven Deutsch
21,046 PointsHey Todd Stacy,
We use an extension when we want to add extra functionality to a type that already exists. This could be a custom type you created or one that is provided in one of Apple's Frameworks. In this challenge, we are being asked to override the String type.
The challenge wants us to create a method called "add" as an extension to the String type. This method will take a single parameter of type Int and have a return type of Int?. Since we are going to be performing a mathematical operation on a String, we need to be able to return nil if the string can't be converted to an Integer. That is why our return type is optional.
Inside the methods body, we first need to check if the string we are calling this method on can be converted successfully to an integer. If it can, we will perform the operation of adding the value we pass in when calling this method to the value of the converted string. If it can't be converted from String to Int, well, we will return nil.
It makes sense to use a guard statement here to achieve this, because we want to make sure that the string can be converted to an integer before we continue execution of this method. If this isn't the case, we will jump into the else block and exit the scope of the function immediately.
// Enter your code below
extension String {
func add(n: Int) -> Int? {
guard let conversion = Int(self) else {
return nil
}
return conversion + n
}
}
Good Luck
Todd Stacy
5,816 PointsTodd Stacy
5,816 Pointsokay i get it now. thank you!