Discover the foundations of iOS Development and the importance of object-oriented programming in Swift. Learn about defining classes, creating custom methods, instantiating a class, and more, all through hands-on exercises and tutorials.
Key Insights
- Object-oriented programming in Swift is based on concepts represented as objects with data fields (properties) and associated procedures (methods).
- Classes in Swift, the foundation of object-oriented programming, function as templates or wrappers for a set of functionalities.
- Methods within classes can accept parameters and return data, much like functions can.
- Properties are constants or variables declared in a class representing the characteristics of objects instantiated from it.
- Instantiation in Swift refers to the process of bringing an object to life using a class as a template.
- Classes in Swift allow efficient setting of values within a class, facilitating the calling of methods by their instance names.
Explore the basics of iOS development and object-oriented programming, including defining classes and custom methods, instantiating a class, and working with properties and methods in this comprehensive tutorial.
This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.
Topics Covered in This IOS Development Tutorial:
Object-oriented Programming, Defining Classes & Custom Methods, Instantiating a Class, Properties, Methods with Parameters, Methods with Return Values
Exercise Overview
In this exercise, you will look at classes, which are the foundation of object-oriented programming (the type of programming language Swift is). Classes are templates or wrappers for a set of like functionalities, and are the building blocks of your app.
Getting Started
Launch Xcode if it isn’t already open.
Go to File > New > Playground.
Under iOS, double–click on Blank.
Navigate into Desktop > Class Files > yourname-iOS App Dev 1 Class.
Save the file as: Classes.playground
Click Create.
Object-Oriented Programming
Object-oriented programming is a programming paradigm (style) that represents concepts as objects that have data fields (attributes that describe the object) known as properties and associated procedures (behaviors) known as methods.
Traditional, non-object-oriented programming is generally linear and not very reusable. It is also difficult to assign meaningful connections between different parts of the code. As a result, the more code there is, the more of a maintenance nightmare it becomes. That’s why object-oriented programming was created.
Instead of executing code line-by-line, objects in Swift send messages to other objects. Because classes are like a blueprint or template for objects, they are the foundation of object-oriented programming.
Defining Classes & Custom Methods
Later on, we will need to use objects from UIKit so delete only the var str line.
-
You define a class by typing class followed by the name of the class. Everything related to the class will be implemented within the curly braces {} following it. Type the following bold code:
import UIKit class Car { }
Classes are usually given a noun for a name. Keeping with the automotive theme, think of a class like the frame of a car that’s used for a variety of models. A car company can create many cars that share the same frame, but have different colors, interiors, and features.
-
In an earlier exercise you learned that methods are like functions but are associated with a type. Classes are a type, so when a function is part of a class, it’s referred to as a method. Create two custom methods for our Car by typing the code below:
class Car { func start() { print("Vroom") } func stop() { print("Screech, halt!") } }
Instantiating a Class
Now that you’ve defined a class and implemented two methods within it, let’s use our Car class as a template to create an object. Objects are instances of classes so the process of bringing an object to life is called instantiation.
-
In order to instantiate, you declare a constant or a variable and set it to a class. To start using the Car class, create an instance of Car at the bottom of the file:
let mustang = Car()
This instance of the Car class is a constant named mustang. Instances are specific objects that have the class’s attributes and actions. (For instance, our mustang can start and stop because it is a type of Car.) Because instances are associated with classes, they are also typically named with a noun.
-
We currently have two methods, start and stop, in our Car class. In order to refer to any of the methods within the class, you access it by using the instance name and dot syntax like so: instanceName.methodName() Below the mustang instantiation, add the following code to start the car:
let mustang = Car() mustang.start()
-
Toward the middle of the file and inside the Car class’s start method, look in the results sidebar. Notice it says: Vroom
NOTE: The results sidebar also prints Car directly to the right of the start method call you just typed. This reminds you which class the method is associated with.
-
Let’s access the stop method. Type:
let mustang = Car() mustang.start() mustang.stop()
Notice in the results sidebar to the far right of the Car class’s start method, it says: Screech, halt!
Properties
Properties are constants or variables that are declared in a class and represent the characteristics of objects we instantiate from it. Take a moment to think of generic attributes for our Car class that you can reuse for different types of cars such as its color or cost.
-
Let’s declare a property for this class. Near the top, add an optional property:
class Car { var speed: Int? func start() {
Here you’ve set a property that can be accessed by our mustang instance or from any one of the methods within the class. We’ll explore optionals in a later exercise.
-
As with methods, you use dot syntax to access the property to set its value. Below the start method call for the mustang instance, set the mustang’s speed to 10:
let mustang = Car() mustang.start() mustang.speed = 10 mustang.stop()
The syntax for declaring a property is: instanceName.property = value
-
Let’s set the mustang’s speed to 0 after it stops. Type:
mustang.start() mustang.speed = 10 mustang.stop() mustang.speed = 0
-
You can actually set property values from within the class itself. Delete both speed value settings so that you’re left with the following:
let mustang = Car() mustang.start() mustang.stop()
-
Let’s set a speed value from within the start method. Type the following bold code:
func start() { self.speed = 10 print("Vroom") }
When you’re within a class, the instance of that class is called self. This is what you’d use when you want to set the value of a property or call a method from within a class.
-
To set a speed value from within the stop method, type:
func stop() { self.speed = 0 print("Screech, halt!") }
-
Now you can print out the speed, using string interpolation. Near the bottom, add the bold code (including the exclamation point to force unwrap the optional property):
mustang.start() print("The speed of the car is \(mustang.speed!) miles per hour") mustang.stop()
On the right it says: The speed of the car is 10 miles per hour
-
To check the speed of the car after it stops, copy the print function and paste a copy of it below the stop method as shown:
print("The speed of the car is \(mustang.speed!) miles per hour") mustang.stop() print("The speed of the car is \(mustang.speed!) miles per hour")
On the right it says: The speed of the car is 0 miles per hour
As you can see, it’s much more efficient to set values within a class. That way you can call methods by their instance names.
Methods with Parameters
Let’s take a deeper look at methods. As mentioned briefly earlier in the exercise, methods are functions that are in a class. Recall that functions can accept parameters and return data, so methods can do these things too.
-
Below the stop method, add a method to the Car class that accepts a parameter for speed:
func stop() { self.speed = 0 print("Screech, halt!") } func accelerateTo(speed: Int) { self.speed = speed }
-
At the bottom of Xcode, call the accelerateTo method as shown in bold, passing in an argument of speed: 50 where the method’s parameter asks for information:
print("The speed of the car is \(mustang.speed!) miles per hour") mustang.accelerateTo(speed: 50)
In the class, mouse over the right side of the self.speed = speed line and click the Quick Look eye
. In the pop-up it says {some 50}, which means that the speed was automatically set to 50.
-
Add a print function to the accelerateTo method:
func accelerateTo(speed: Int) { self.speed = speed print("The speed is now \(self.speed!) miles per hour") }
Notice in the Playground results sidebar, to the right, it says: The speed is now 50 miles per hour
Methods with Return Values
It would make sense for us in our Car class to determine how much gas is used and to set a property for the miles per gallon for our car. You’ll start by setting an optional property for miles per gallon.
-
Towards the beginning of the class, add another property for mpg:
var speed: Int? var mpg: Float? func start() {
-
We only have one instance of the Car class right now, but we can add more later. Because the mpg property is part of the class, we can set different mpgs for each type of car. This is a good example of how object-oriented programming comes in handy. Under the mustang’s instantiation, set the mpg for mustang:
let mustang = Car() mustang.mpg = 30.0 mustang.start()
-
At the bottom of the Car class, add the following bold method with a return type for the amount of gas used:
func accelerateTo(speed: Int) { self.speed = speed print("The speed is now \(self.speed!) miles per hour") } func gasUsed(milesDriven: Float) -> Float { } }
To make the red error go away, let’s pass in the miles driven, then calculate the gas used and return it.
-
Fill in the method by creating a constant to store the data:
func gasUsed(milesDriven: Float) -> Float { let gas = milesDriven / mpg! return gas }
Now our method calculates the gas used based on the mpg property value that you assigned the car earlier (mustang.mpg = 30.0).
-
At the bottom, set a constant and pass in the argument for how many miles were driven:
mustang.accelerateTo(speed: 50) let theGasUsed = mustang.gasUsed(milesDriven: 100.0)
At the bottom of the results sidebar on the right, you should see the amount of gas used: 3.333333
Save the file and keep Xcode open so that we can continue with this file in the next exercise.