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 Complex Data Structures Adding Instance Methods

Maxwell Catmur
Maxwell Catmur
7,355 Points

How do you create instances in methods?

Please can you help e with this challenge? Here's the question:

Let's use the struct to create an instance of Person and assign it to a constant named aPerson. Assign any values you want to the first and last name properties.

Once you have an instance, call the instance method and assign the full name to a constant named myFullName.

Code is attached below. It would be great if you could let me know what is wrong please. Thanks

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

    func fullName() -> String {

        let aPerson = Person(firstName: "Marcus", lastName: "Lanny")
        return firstName + " " + lastName
    }

    let myFullName = fullName()
}

1 Answer

Aryaman Dhingra
Aryaman Dhingra
3,536 Points

There are a couple places where you are going wrong in the challenge. Firstly, in the fullName() function, all you need to do is to do String interpolation with the First and Last name values that will be provided when an instance of the Struct is created. Like this.

func fullName() ->String {
     return "\(firstName) \(lastName)"
     // both firstName and lastName are provided when instance is created
}

Secondly, you're creating an instance of a struct inside the struct's definition, and I'm not sure but I don't think this really works as it would cause some sort of mess up. The task asks for an instance of the Struct outside of the structs actual definition. And then after you have that instance of Struct, you need to call the fullName method on it to get a fullName in one string value. Kinda like this.

} //struct ends here

let aPerson = Person(firstName: "Marcus", lastName: "Lanny")
let myFullName = aPerson.fullName()

If this helped, don't hesitate to mark it as the best answer!

Maxwell Catmur
Maxwell Catmur
7,355 Points

Hi Aryaman,

Thank you very much. I'm just about getting the hang of object oriented swift and structs.

P.s Sorry for the late response!