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

I don't know what's going on. Method instance was created, but I cannot pass the challenge.

Can someone give me little explanation of instance methods use. Maybe little code example with comments what's going on step by step.

struct Person {
    let firstName: String
    let lastName: String
    func fullName(name: String, surname: String)->(Person){

        let fullName = Person(firstName: "P", lastName: "K")
        return fullName
  let myName = Person(firstName: "P", lastName: "K")

1 Answer

Hi Piotr!

So the first question is asking you to create a method in the struct called "fullName" that returns a String.


 func fullName() -> String {
     // Here you would return the firstName and the lastName
     // One way to do this would be string interpolation where you take the Constances and pass them through a string
     // Like this: 
     return "\(firstName) \(lastName)"

The second question specifically asks you to "use the struct to create an instance of Person and assign it to a constant named aPerson"

Any time you make a custom version of a "class" or "struct" (in this case a struct...) you are creating an "instance" of that thing. So that's what creating an instance means. Making a custom version of it.

// Making an instance of Person :)
let aPerson = Person(firstName: "P", lastName: "K")
// Then they want you to 
let myFullName = aPerson.fullName()

Next bit to understand is that structs get a free "init" method. and the init method is what is called after typing "(" after the struct or class name. But if this was a class you would have had to make the init method from scratch inside of the class body. Example:

class Person {
    let firstName: String
    let lastName: String

    init(firstName: String, lastName: String) { // this is where you would have had to create an init from scratch with the parameters you would need to populate the constance

          // Here you have to set the constance of self(the class your in) equal to the parameter value you want it to be...
          self.firstname = firstName
          self. lastName =  lastName

Happy Coding :)