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 trialpradeepchandrasekaran
2,731 PointsHow to add an instance method to the struct definition
Can somebody explain me how to add an instance method to the struct definition for this task ?
struct Person {
let firstName: String
let lastName: String
func getFullName(firstName: String, lastName: String) -> [Person]
{
let fullName = "\(firstName) \(lastName)"
return fullName
}
}
getFullName("Pradeep", lastName: "Chandrasekaran")
1 Answer
Jordi Gámez
3,568 PointsHi Pradeep,
You have to first create an instance of the struct Person, that's what happens in my constant "myPerson" and you have to send the parameters for firstName and lastName.
After that, you only have to call your getFullName method, and you don't have to send again the parameters because you have already access to them since you have initialized your struct myPerson.
Here you are the answer:
struct Person {
let firstName: String
let lastName: String
func getFullName() -> String {
let fullName = "\(firstName) \(lastName)"
return fullName
}
}
let myPerson = Person(firstName: "Pradeep", lastName: "Chandrasekaran")
myPerson.getFullName()
pradeepchandrasekaran
2,731 Pointspradeepchandrasekaran
2,731 PointsJordi Gámez - It helped. Thank you :)
Steven Deutsch
21,046 PointsSteven Deutsch
21,046 PointsJordi Gámez already took care of things here, however, I just thought I would suggest returning the string literal directly instead of assigning it to a variable/constant. If you are not going to use the variable elsewhere in the functions body, it doesn't make sense to create one. Just return the desired result directly.