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

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! :)