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 trialMichael touboul
3,053 PointsStruggling to understand class and struct...
Hello everyone, am I the only one here who is very confused regarding struct and classes...? I understood all the learning parts until Passan started with the "struct" - I am having major difficulty understanding everything, am I the only one here? what can I do to continue, I really need some advice here, thx.
1 Answer
Caleb Kleveter
Treehouse Moderator 37,862 PointsYou might want to read this document about choosing a struct or a class.
I don't know if this has been covered at this point in your learning, but the biggest difference you will see in working with classes vs structs is how that actual data is handled when an instance of a type is created.
Let's say I have a User
struct:
struct User {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
var userOne = User(name: "Caleb", age: 18)
var userTwo = userOne
userTwo.age = 19
print(userOne.age) // 18
print(userTwo.age) // 19
If I copy the instance of a struct and mutate the copy, the original will not be modified. But If I do the same thing with a class:
class User {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
var userOne = User(name: "Caleb", age: 18)
var userTwo = userOne
userTwo.age = 19
print(userOne.age) // 19
print(userTwo.age) // 19
If I mutate the copy of a class instance, the original is updated. This is one of the biggest noticeable differences between a struct and a class.