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 trialNehemiah Reese
17,692 PointsCan anybody help with the "Extend a Native Type Challenge?" Here is my code:
extension String { func add(i: Int) -> Int? { if self.intValue { return self.intValue + i } else { return nil } } }
// Enter your code below
extension String {
func add(i: Int) -> Int? {
if self.intValue {
return self.intValue + i
} else {
return nil
}
}
}
1 Answer
Greg Kaleka
39,021 PointsHi Nehemiah,
You're close, but there are two issues with your code:
- Swift Strings don't have a property intValue like NSStrings do.
- In Swift you can't use an if statement like that - you could say
if thingThatMightBeNil != nil
, but using guard or if let is better
Here's a solution using if let:
// Enter your code below
extension String {
func add(i: Int) -> Int? {
if let numberFromString = Int(self) {
return numberFromString + i
} else {
return nil
}
}
}
and here's one using guard, which I prefer in this case:
// Enter your code below
extension String {
func add(i: Int) -> Int? {
guard let numberFromString = Int(self) else {
return nil
}
return numberFromString + i
}
}
Let me know if any of this doesn't make sense!
Happy coding
-Greg
Nehemiah Reese
17,692 PointsNehemiah Reese
17,692 PointsThanks! Makes perfect sense now. I was looking into the NSString documentation lol. I'm sort of a newbie at programming still polishing up.
Greg Kaleka
39,021 PointsGreg Kaleka
39,021 PointsAwesome - glad I could help!