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 Object-Oriented Swift 2.0 Complex Data Structures Adding Instance Methods

pradeepchandrasekaran
pradeepchandrasekaran
2,731 Points

How 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 ?

structs.swift
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
Jordi Gámez
3,568 Points

Hi 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()
Steven Deutsch
Steven Deutsch
21,046 Points

Jordi 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.

struct Person {
    let firstName: String
    let lastName: String

    func getFullName() -> String {
        return "\(firstName) \(lastName)"
    }
}

let myPerson = Person(firstName: "Pradeep", lastName: "Chandrasekaran")
myPerson.getFullName()