Learning Swift and iOS Development Part 10 : Classes

JonnyB
6 min readMar 1, 2018

--

If you are just starting your learn-to-code journey, you may have heard of Object-Oriented Programming.
It’s a widely popular and highly revered model for programming that has stood the test of time. It is starting to get to a point where it may be replaced by other more modern models like Protocol-Oriented Programming, but it’s still very important to understand.

Classes are a key component of OOP (Object-Oriented Programming) which allow us to create a blueprint of sorts and then copy it and modify it as needed.

An example could be a car in a car factory. Imagine an engineer created a blueprint for a car. In the factory, you can use that blueprint to create multiple copies of the same car by following the plans laid out in the blueprint.

Let’s create our first class and use the car example from above.

Setting up

First, open Xcode if you haven’t already and click Create New Playground.
Give it a name like “Classes” and click Next.
Choose somewhere to save this .playground file and click Create to save it.
You should see a screen like the one below.

Delete all the boilerplate code on the left side but leave import UIKit as it is necessary.

Creating your first Class

In your Playground window, create a class by typing the following:

class Vehicle {}

We used the keyword class followed by the name of our class Vehicle.

It is best practice to start your class names with a capital letter (i.e. Vehicle, Motorcycle, Scooter).

Adding Variables And Functions

Now, we need to add in variables for properties that we want all of our cars to have. Like so:

class Vehicle {
var tires = 4
var headlights = 2
var horsepower = 468
var model = ""

func drive() {
//Accelerate the vehicle
}

func brake() {
//Stop the vehicle
}
}

As you can see, a class can have properties (i.e. tires, headlights, horsepower, model) and functions (i.e. drive(), brake()) to describe it.

Understanding OOP

To understand OOP, you really need to try to visualize the world around you. This concept is usually pretty easy to understand for people who are more artistic and have a designer brain because you can easily visualize things as objects.

If your brain operates more on the numbers and logic side, this can be difficult to understand because you may want to turn it all into numbers or algorithms of some kind.

Here’s another example, I hope this helps to explain OOP a little more.

Instagram has users who can like other photos, so you may have a User object which contains a user id, account, password, amongst other properties.

This user may also have functions like: resetPassword() or deleteAccount. Even the photos on Instagram could be objects.

If we have a Photo class, it may have properties for: selectedFilter, numberOfLikes, numberOfComments.
Some functions a Photo may have could be: addLike(), removeLike() — kind of actions to perform on that object.

Start trying to look at objects in the real world in regards to their properties and functions (what they’re like and what they do).
Everything around you can be put into an object in code.

Creating an Instance of a Class

Let’s create an instance of our Vehicle class by adding the following at the bottom of our Playground:

let delorean = Vehicle()

We created a constant called delorean and initialized it as an instance (or copy) of our Vehicle class by typing “Vehicle” and following it with parentheses.

The model property from above is initialized as an empty String above, so let’s give our car a model name.

let delorean = Vehicle()
delorean.model = "DMC-12"

Create a few more instances of our class at the bottom of the Playground:

let delorean = Vehicle()
delorean.model = "DMC-12"
let bmw = Vehicle()
bmw.model = "328i"
let ford = Vehicle()
ford.model = "F150"

Can you see what’s happening? We wrote the code for a Vehicle once, but we created multiple instances of that code and setting the properties of it.

We can also call the functions for Vehicle as well. Just so you’re aware, once we create an instance of a class, we call it an object.
Just like when the car leaves the factory it’s then considered an object.

Try this out by adding the following to your Playground:

let delorean = Vehicle()
delorean.model = "DMC-12"
delorean.drive()
let bmw = Vehicle()
bmw.model = "328i"
let ford = Vehicle()
ford.model = "F150"
ford.brake()

We called drive() on our delorean object and brake() on our ford object.
We’ve told these objects to do something.

Again, think of a class like a blueprint — does it have any properties I should note? Are there any abilities it has or things it can do? In most cases, the answer will be yes.

Classes Are Reference Types

In Swift, there are reference types and value types. They are different, but we only need to know about reference types today.

I won’t be going in depth into what it means, only what it means for you as the reader right now.

To demonstrate how classes are reference types, add the following function and print ford.model at the bottom of your Playground:

func passByReference(vehicle: Vehicle) {
vehicle.model = "Cheese"
}
print(ford.model) // Prints "F150"

Next, call passByReference(vehicle:) and pass in the ford model:

func passByReference(vehicle: Vehicle) {
vehicle.model = "Cheese"
}
print(ford.model) // Prints "F150"passByReference(vehicle: ford) // Pass the ford class by referenceprint(ford.model) // Prints "Cheese"

I thought when we declared ford we made it a constant by using let!
How is it that the model value can be changed? Well, to put it simply an object has a reference in memory.

You can’t copy an object. Things like Integers and Doubles can be copied because they are value types, but not objects.

Here’s another example to show how passing by reference works. Add the following variable and function to the bottom of your Playground:

var someonesAge = 20func passByValue(age: Int) {
age = 10
}

You probably notice that Xcode displays an error saying that age is a let constant.
Because an Integer is a value type, we can’t modify it in the same way we can a reference type. Let’s try calling our function and passing in someonesAge:

var someonesAge = 20func passByValue(age: Int) {
age = 10
}
passByValue(age: someonesAge)

Xcode won’t allow for this to work. Reference types can be modified and they are stored in a specific place in memory, but value types (i.e. Integer, Double, Float, etc.) cannot be modified, but can be copied.

Wrapping up

This post covers the basics of Classes in Object-Oriented Programming. A class can contain properties that describe it and actions (functions) that it can perform.

We can create a copy of a class by instantiating it as well. While this may still be confusing, you will continue to use it in context throughout this series which will help you rapidly gain understanding.

Continue to do your research and always stay curious about learning to code. Don’t ever settle with doing enough or knowing enough. There are always ways for us to improve and become better programmers.

Exercise
Create another instance of the Vehicle class for a car of your choice. Be sure to set a value of type String for the model property. Create a separate class named Smartphone and include some properties and/or functions that all smartphones need. Create an instance of the Smartphone class called iphone and another called android and set the properties to be unique to those devices. Create another instance of the Smartphone class for another type of smartphone.

If you want to learn more about Swift and iOS development, head over to www.devslopes.com and enroll in our Apple Developer Slope where you’ll learn everything you need to know to develop iOS apps. ❤️

--

--

JonnyB

Passionate about coding. Developer and Teacher at Devslopes.