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

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?