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

Cody Adkins
Cody Adkins
7,260 Points

What situation would it be better to use a struct in, over a enum?

Can someone give me real life examples in a popular application?

1 Answer

Nathan Tallack
Nathan Tallack
22,159 Points

Enums in Swift are insanely awesome. So this answer may not be aligned to ther languages, but for Swift it is valid.

Enums are great for safety!!! The finite nature of them make them fantastic for objects that are taking input from the user. So first and formost, if you are taking something in from the user and you need it to be safe, enums are for you! Enums are also great for storage. Being able to use things like Ints for associated vlaues mean that you can have your objects respresented in persistant storage with a whole lot less space. Makes it great for iCloud type solutions too. Less data is good!

Now if the enum is not the right choice, then it comes down to a struct or a class. You'd choose a struct when inheritience is not required. Where each object stands alone. You'd use a struct where you are going to pass around individual items of unrelated data. So if you need to have objects that standalone and are unrelated, structs are great for that.

Remember, there are COUNTLESS other reasons that help guide your decision about which object type to use. But these ones above are often the most comon ones you will encounter at beginner and intemediate programming levels.

I hope this helps. And please, if you are an boss level programmer and you see errors or shortcomings in my not boss level info above, PLEASE correct me!!! I want to learn too!!! :)