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

What's the difference between Classes and Structs in Swift?

i am not understanding the difference between the two. What are the advantages and disadvantages of both?

They both have properties and methods.

Any help appreciated :grin:

~Alex

2 Answers

Allen Soberano
Allen Soberano
13,634 Points

I'll try to give an example, I had a difficult time distinguishing the differences as well but hopefully this helps.

Think of grocery shopping. There are carts and items.

Everyones carts have different items. (Good case for structs because there are multiple carts but you can change what items you put in the cart): Passed by Value

Everyone is paying the same price for a specific item. (Good case to make items classes because if you change the price on a can of Beans, then the price is changed on that can of Beans in everyones cart.): Passed by Reference

https://teamtreehouse.com/library/objectoriented-swift/value-vs-reference-types/structs-vs-classes

Oooh! I understand now! Thank you! :smile:

Allen Soberano
Allen Soberano
13,634 Points

Just glad I could be of help for a change. :)

Allen Soberano
Allen Soberano
13,634 Points

One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference.

As you progress down a couple more videos Pasan goes over the main difference I have stated above.

What do you mean?