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 Object-Oriented Swift Classes in Swift High Level Overview

Struct vs Class

the only difference i see between struct and a class is the (init) and i would like to know when do i use struct and a class?

2 Answers

Rebecca Jensen
Rebecca Jensen
11,580 Points

I had the same question and found this article to be helpful:

https://learnappmaking.com/comparing-classes-vs-structs-swift/

In short, a struct creates a copy of data (it is a value type) while a class creates a reference to it (it is a reference type). This is the example used in the article:

"Reference Type: Bob has a phone number. He gives it to Alice. Alice doesn’t write down the phone number for herself, but instead remembers that Bob has it. When she needs the phone number, she asks Bob. When Alice accidentally changes one digit of the phone number, Bob’s phone number changes too. (You could picture this as Bob and Alice both holding the piece of paper the phone number is written on.)

Value Type: Bob has a phone number, and he gives it to Alice. Alice writes it down and now has her own copy. When she accidentally changes it, only her copy changes, and not the original phone number Bob has."

So it boils down to choosing the right one for the task, depending on whether it makes sense to copy data or make a reference to the original. The pros and cons of copies vs. references isn't entirely clear to me yet, but hopefully this helps answer your question somewhat.