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 Swift Enums and Structs Structs and their Methods Initializers

Josh Schlabach
Josh Schlabach
1,771 Points

Why are initializers used?

I'm confused. Why do we need an initializer in our struct? Can someone give me a real life world example? Just a little confused.

2 Answers

As the video showed. Your struct have an initializer by default. However, that initializer requires you to specify all the values. If you want to avoid that behaviour you need to specify your own init function. When you do that, the default init is overridden and your function will be used instead. On that function you can ask for specific values.

Structs are similar to objects.

The parameters to init( param1: value, param2: value) can be passed through so you can pass through multiple values to the stored property of your struct. it is interesting, that you can do this easily with enums with this new swift protocol.