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 trialAlexander Davison
65,469 PointsWhat'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
~Alex
2 Answers
Allen Soberano
13,634 PointsI'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
Alexander Davison
65,469 PointsOooh! I understand now! Thank you!
Allen Soberano
13,634 PointsJust glad I could be of help for a change. :)
Allen Soberano
13,634 PointsOne 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.
Alexander Davison
65,469 PointsWhat do you mean?
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsTagging Pasan Premaratne