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

initializers

can someone tell me how exactly do you create an initializer, I still got a problem. I especially don't know what those parentheses are for, and when you need it. Thanks

1 Answer

Alexandre Attar
Alexandre Attar
10,354 Points

I'll try my best to explain what they are and what's the point for us use them.

So first, 'Intializers' are to create a new instance of a type. It's basically provides an initial values for our class' and struct's properties.

Here is code snippet to help you understand this better:

struct PersonA {
    let firstName: String
    let lastName: String

    init() {
        firstName = "Tim"
        lastName = "Cook"
    }

}

struct PersonB {
    let firstName: String
    let lastName: String

}

let aPerson = PersonA()

let bPerson = PersonB(firstName: "Tim", lastName: "Cook")

Our constant aPerson will have the have the values as our bPerson constant. However, as you can see for our aPerson constant since the struct was already initialized we didn't have to provide values for 'firstName' and 'lastName' since it had a default value.

Now how do you create an initializer? Well, you can either do it like we did above by including it inside your struct or class. Or you could do this:

struct PersonB {
    let firstName: String
    let lastName: String

}

let aPerson = PersonA()

let bPerson = PersonB.init(firstName: "Tim", lastName: "Cook")

When it comes to the parentheses '()' they are there since init is a method. Like every method when you call it you need to put the parentheses at the end.

It's already a long post but if I wasn't too clear or need more information just let me know!

Happy coding!