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 Custom Initializers

Dom Anca
Dom Anca
931 Points

I'm really confused as to what init actually does

I get that for this step we don't actually need to use init as Swift does this for us, but I can't understand when we would ever need to use init. I also don't understand what a memberwise init is. If anyone could help I would be soo grateful, this is all so confusing haha

1 Answer

Hi :)

When I am starting my tech degree in treehouse I am also with the terminologies use in Swift.

Here is the example where is good to use a init in a struct. Below I will get a value from a dictionary and I don't want to initialize the struct using all of it's properties so I am going to create a init method.

struct CarInfo{
     let wheels: Int
     let doors: Int
     let model: String


     init (dictionary: [String: Any]) {
         wheels = dictionary["Wheels"]
         doors = dictionary["Doors"]
         model = dictionary["Model"]
     }
}

let car1 = CarInfo(dictionary: [dictioanry here])

And this the example where is good to use a memberwise initializer.

struct Person {
     let lastName: String
     let firstName: String
}

let person1 = Person(lastName: "Persone", firstName: "One")

So here, you don't need to create a init method because Swift will handle this for you.

Dom Anca
Dom Anca
931 Points

First of all thank you so much for taking the time to answer my question I’m still a little lost- it seems that with your examples there isn’t any difference in functionality that I can see. Would you be able to tell me precisely what extra functionality you could want that would make you use init instead of just letting swift do it for you? Thanks again Dom