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

Eli MBS
Eli MBS
1,158 Points

Instance

How do I create an instance of this code?

structs.swift
struct Person {
    let firstName: String
    let lastName: String
    func getFullName(firstName: String, lastName: String) -> String {
        return "\(firstName) \(lastName)"
}

1 Answer

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

Before you do that, you need to fix a couple things with the function in your struct.

Your function should not pass any parameters. If it did, then your function would allow anyone who uses the function to put in any firstName and any lastName and use them for the Person's fullName, whether or not those are actually the Person's firstName and lastName.

Your function also needs a closing curly brace at the end of it.

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

To create an instance of a Person: it's pretty much the same as instantiating anything else. If you want a constant, use the let keyword; if you want a variable, use the var keyword.

let aPerson = Person(firstName: "Harry", lastName: "Dresden")

I hope this helps!

Eli MBS
Eli MBS
1,158 Points

Thank you for your help! I still get an error:

struct Person { let firstName: String let lastName: String func getFullName() -> String { return "(firstName) (lastName)" } let onePerson = Person(firstName: "Max", lastName: "Maxi")

(How do I put the code in the same "box" as you do?)

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

You need another closing brace to close off your Person struct.

To put the code in the box, you use three tics (`), which can be found on the upper left corner of your keyboard, to encapsulate your code. I'm going to use "tic" instead of the tic mark in the example below, which I'm putting in a box to make the formatting nicer.

tictictic[CODING LANGUAGE IN LOWERCASE]
// INSERT CODE HERE!
tictictic

So, if you wanted to write the following code:

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

You would write this, replacing tic with `:

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

If you want more information, click the "Markdown Cheatsheet" link underneath the comment box or the answer box.

I hope this helps!