DEV Community

Logan
Logan

Posted on

100 Days of Code: Day 2

I'm almost done for today, but I wanted to make sure I got this down I shut down.

Today I learned the prime differences between class and struct. In general, it's recommended to default to a struct because they create new instances of an object rather than point to the same object in the way that classes do.

Example: If I have struct of my fat cat, Thor. He can be initialized and create a whole new Thor. Any changes to your Thor, like actually getting him to lose weight and not be such an asshole, would only apply to that particular instance of a Thor. My Thor would continue to yell at me any time I go into the kitchen because he hasn't gotten a treat for... I'm not sure why he thinks he deserves them.

But with a class, any instance of a Thor points back to the same foul tempered chunk. I don't hate Thor. Far from it, we're at that point in our relationship where we can we can look each other in the eye and call each other scum, but know we mean the opposite.

Maybe this will help explain what I mean.

struct Thor {
var weight: Int
var attitude: String
}

You could initialize and clone that Thor all you wanted
`var thor1 = Thor(weight: 100, attitude: "shit")
var thor2 = thor1
And so on. Any changes to thor1, would be completely independent of any changes to thor2.

You could thor1.weight = 13 and thor2.weight would remain unchanged at 15. Still just as fat as ever.

If you tried to do the same thing with a class, it's a different story...

class Thor {
var weight: Int
var attitude: String

init(weight: Int, attitude: String) {
self.weight = weight
self.attitude = attitude
}
}

First thing you'll notice is the memberwise initializer inside the class. Had there been a default value for weight and attitude, we could have skipped it like we did with structs. Those values will still have to be passed when the object instance in created, but it's not necessary. Without default values and only types, they are necessary. Xcode will remind you before you even get to that line.

Now let's make some cats.

var thor3 = Thor(weight: 15, attitude: "hungry")
var thor4 = thor3

If you did a thor3.weight = 13, then thor4 would also have the weight property value of 13. That's because unlike a struct that constantly creates new instances of itself when there's changes and re-inits, a class points back to the same initial instance. Like a cat thinking that every time I go to the kitchen, it's to feed them.

There's more to difference that just this. You can sub-class a class, but you can sub-struct a struct. That's another conversation, but I really feel that this is the main thing for me to take away from today.

That and I love this little guy:
Thor

Top comments (1)

Collapse
 
tatacsd profile image
Thays Casado

Hahaha nice explains about class 😂