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 Build a Weather App with Swift Managing Complexity Network Operations

Giedrius Zavadskas
Giedrius Zavadskas
6,427 Points

Why class and not struct?

I saw you used a class and not a stuct in this case. Not sure why..?

Nathan Bills
Nathan Bills
5,449 Points

Good question, Giedrius. I looked at the "Comparing Classes and Structures" section of the Swift documentation on Classes and Structures and couldn't find anything definitive. However, just below that section, there is a note:

"Structures are always copied when they are passed around in your code, and do not use reference counting"

I wonder if that means there could be multiple instances of the NetworkOperation object if it were a struct instead of a class which would defeat the purposes of saving memory resources by lazy-loading. Does that sound right anyone?

Giedrius Zavadskas
Giedrius Zavadskas
6,427 Points

Nathan,

Thanks for your comment. Good thinking!

It might have to do with inheritance as well.

I happened to come accross this stackoverflow post which I found helpful: http://stackoverflow.com/questions/24232799/why-choose-struct-over-class. I found it a bit strange that Apple's Swift book was somewhat misleading here too...

1 Answer

Tal Zion
Tal Zion
6,234 Points

Hi Giedrius,

Good question indeed. I think it would be more important to understand the differences of one another to know how to implement within your code.

Let's take two Object examples,

Object A - Product Object B - User

For Product, you would use Class. The reason is, is when you copy the object, you would initiate a new instance of the class, so technically, you have created a new product.

With user, you woulds use Struct, so when you assign the User to a new object, you would only pass the reference in memory to the same object. You wouldn't want to have "multiple User objects" in your code.

To summarise,

Class - always created an instance of the class Struct - will pass on the reference top the same object.

Hope this helps and I have explained myself in an easy way to understand. Please get in touch if you have any questions.

Tal