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 trialStuart Robertson
Courses Plus Student 1,296 PointsExtending With Native Types Code Challenge
Hey, I was trying to make a function out of this, but I can't remember how or if there is a way to convert one type to another. If anyone knows how please tell me, and also if I am on the right track or going about this completely wrong. Thanks!
// Extending A Native Type
extension String {
var add: String {
func AddingWithStringAndInts(let integerInt: Int) -> String {
return self + integerInt
}
}
}
2 Answers
jcorum
71,830 PointsFirst, they want a function, not a variable. Second, it needs to take an Int and return one, but since nil is a possible return value it has to be an optional Int. Third, you need to convert the String to an Int, and you need optional binding, because the String may be something like "a" rather than "2", i.e., a String that could not be converted.
extension String {
func add(x: Int) -> Int? {
if let y = Int(self) {
return y + x
} else {
return nil
}
}
}
larry sigo
4,067 Points extension String {
func add (value: Int) -> Int?{
//return an integer value if the string can be converter to an integer
if let intValue = Int(self) {
return intValue + value
}else{
return nil
}
}
}
Stuart Robertson
Courses Plus Student 1,296 PointsStuart Robertson
Courses Plus Student 1,296 PointsOh thanks for that, much appreciated!
Jens Hagfeldt
16,548 PointsJens Hagfeldt
16,548 PointsThanks jcorum, that helped me a lot!