Welcome to the Treehouse Community
Looking to learn something new?
Struct, Func, Class and Init. The difference between the 3
I've watched the videos and I've read up on it in apple developer library but I'm still confused on when each should be used. Can someone help explain the difference or when it'll be appropriate to use them.
Does Class have a similar role to what is found in RoR. Thank you everyone who helps me understand how to use them correctly when coding.
Nathan Tallack22,158 Points
Firstly, value types and refrence types.
An int and a struct are value types. That means when you creating them you are refrencing the acutal values in memory. And when you copy them around (that is reassign them to another value type) you are creating new copies of them in memory. If you make changes to the original the new one does not change.
A class is a refrence type. This means when you are creating them you are refrencing an address in memory where the object is stored. When you copy it around you are copying that refrence to that address which means you are not creating new copies of that object you are just creating mutliple "copies" of them you are just copying the refrence to the same object. If you make changes to the original you make changes to the new one.
Additionally, an Int stores just one value. A struct and a class can store multiple values (called properties) and can store code (functions inside of these objects are called methods) that let you interact with that object and its properties.
Finally, a class can be subclassed, meaning you can create a subclass that has all of the properties and methods of a parent class inside of it. You cannot do that with a struct.
Many many other things, but that will do for now. That's the most important stuff. :)