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 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.