Classes in Swift for Newbies
In the previous article I talked about structures so I only thought it was right to follow that up with
Classes like a mold that a manufacture uses to produce a product. You can create many products based off that one mold. Using one mold(
class) you can create multiple products(
objects) based off the attributes(
properties) that each mold has like shape, size, etc.
Let’s take a look in code
Open up playground to follow along.
This is the basic syntax of
If your familiar with structs, you will notice how similar class syntax is.
Let’s say we have a simple example of a
In this class we will have
properties of name and age, then we will give it an
initializer is a method we run whenever we try to create a
In the initializer we pass parameters that makes up the Person.
We simply create a variable named
person1 equal to
class which when we add a parenthesis it’ll ask us for the parameters we stated in our initializer.
Now we can now use our
person1 object and grab their properties.
Functions in classes
We can also use functions within our class which will give our person object the ability to call.
getName() we are returning a
String saying “Your name is _____”
We can access our functions through our
Classes are Reference Types
Classes are reference types while structs are value types. I’ll demonstrate how reference types work.
If you would like to learn about structs and value types go to my previous article.
If you were to create a new object,
person2 like so:
Then create a variable,
person3 equal to
Then we change person3’s properties let’s see how it’ll change person2.
age of 55.
Now let’s read both person2 and person3’s age.
You can see there both equal to the same age.
This is because person3 is essentially person2.
When we store a class we are storing this information in memory and person2 is holding a reference to where that data is.
When we make person3 equal to person2, we simply look at that same reference place for that data.
Person3 is NOT a copy of person2. It IS person2.
Hope that makes sense.
This is very barebones article on classes, I’m planning on also covering inheritance of classes in another article.
I hope this was easy concept to grasp as I tried to explain it simply. If you had any questions or suggestions feel free to let me know.
If you got stuck during the guide, I’ll have sample code up on my GitHub for you to check against yours to see where your going wrong. Or simply let me know and I’ll do my best to help. 😊
Thanks again for reading!