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

Struct or class?

When i use a Struct and when i use a Class in swift? What is the diference?

1 Answer

Hi Bruno Arizio,

Without confusing you with a bunch of technical speak here are the basic.

Struct's

Struct's are useful for simple data management that pass between various parts of your code, they are useful in the sense that no changes can be made to a struct instance once created which is defined as an immutable data type. If for instance you have a bunch of weather data a struct would be good to handle this as you don't expect the application to change anything inside the given instance.

One thing to keep in mind is you can alter structs but you first need to prepend the keyword mutating before any method within the struct that is required to make changes to the already present data.

Classes

Unlike a struct, classes are mutable data types meaning whenever you pass an instance of a class around your code base it can be modified by any other part of the code which can lead to incorrect or even unusable data if not managed correctly throughout it's lifecycle.


Hope that helps.