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

Enums vs. Structs vs. Classes

I'm looking for a bit of help with data structures.

When is it appropriate/most common to use an enum vs. a struct vs. a class, and why?

Thanks!

2 Answers

Hi, most often you will use classes as it is the base level data structure: iOS along with other platforms has interface and implementation based on classes. In the interface you would declare your local variables and constants and you would make prototypes of functions (methods of the class) which include just signatures of the methods (name, parameter list and return type):

func calculateArea(withWidth width: Int and height: Int) -> Int

Then you switch to the implementation file and `implement' you variables and methods (fulfill your methods, use your variables):

func calculateArea(withWidth width: Int and height: Int) -> Int {
      return width * height
}

STRUCT is a local data structure and you use it whenever you are already inside a class and you have to create a class-like data structure with less functionality (no inheritance or polymorphism):

Classes and structures in Swift have many things in common. Both can:

* Define properties to store values

* Define methods to provide functionality

* Define subscripts to provide access to their values using subscript syntax

* Define initializers to set up their initial state

* Be extended to expand their functionality beyond a default implementation

* Conform to protocols to provide standard functionality of a certain kind

BUT Classes have additional capabilities that structures do not:

* Inheritance enables one class to inherit the characteristics of another.

* Type casting enables you to check and interpret the type of a class instance at runtime.

* Deinitializers enable an instance of a class to free up any resources it has assigned.

* Reference counting allows more than one reference to a class instance.

And ENUM is even more specific, you use it whenever you know that the structure will only have certain values, like there are only 12 month in a year, so it is pretty efficient to describe and implement the Month data structure as enum

Stepan Ulyanin that was a seriously great answer, I didn't expect anyone to take the time to write that. Thank you!

You are very welcome!