Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Object-Oriented Swift 2.0 Complex Data Structures Adding Instance Methods

Sheng Wei
Sheng Wei
4,382 Points

[Help!] Unsure of correct syntax for this simple method

Task: Add a method that returns the person’s full name. Declare a method named getFullName() that returns a string containing the person’s full name. Note: Make sure to allow for a space between the first and last name

This should be really doable, I just can't seem to figure out the correct syntax after fumbling around. Please help!

structs.swift
struct Person {
    let firstName: String
    let lastName: String

    var fullName = (firstName  lastName)
    func getFullName() {

    return fullName

    }

}

1 Answer

Sheng Wei Pang, the function is inside the struct so it has access to the firstName and lastName member variables. So all you need do, in the function, is return those values in a String, using String interpolation. (Concatenation may also work, I didn't try that.)

struct Person {
    let firstName: String
    let lastName: String

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

let aPerson = Person(firstName: "Wei Pang", lastName: "Sheng")
let fullName = aPerson.getFullName()

Then, you create a Person object, aPerson, and pass in a first and last name. These are stored in the object's member variables, so when you call the getFullName() function on that object you get the full name back.

Sheng Wei
Sheng Wei
4,382 Points

Thanks jcorum, that was really helpful! :)