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

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.

structs.swift
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")
myName.firstName

1 Answer

Hi Piotr!

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

example:

 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:

/**
 ONCE AGAIN THIS IS ONLY AND EXAMPLE FOR IF THIS WAS A CLASS
*/
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 :)