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

When to use Classes over Protocols and Structs over Enums?

Hi All,

I'm having a difficult time knowing when to use a Class over a Protocol or Struct over an Enum.

Is there a general rule that I'm not aware of when deciding what's best.

Hope someone can help me.

Thanks, Michael J

1 Answer

Let's first talk about Class vs. Protocol

A class and protocol are very similar, but a protocol defines the necessary components something must have, and the class simply say what is included. There is an example that you can see in the Swift Protocols course. You can have a class called plane, and a subclass of jet plane. You can inherit all the properties from airplane to jet plane and add on more. However, if you have a class called bird, it will be kind of awkward. A bird is not a type of airplane and an airplane is not a type of bird, in this loose relationship, you would use a protocol. The protocol can be something like Flyable, and it defines all the necessary components for flying. The class can inherit from that protocol, and things will make sense. I am not sure if I have the best explanation here, but be sure to check out this course for more info and explanations. https://teamtreehouse.com/library/swift-20-protocols If you want to learn more about protocols, you can check the Apple documentary. https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

As for struct and enum, it is a lot simpler to explain. An enum is like a multiple choice. You choose the value instead of creating a value, even though you can pass in values in enum also, but think of it as a multiple choice. Struct is similar to class, you create the values and modify things and treat it like an object.

Hope that helps you :)

Okay, that really does help.

Thanks!!