Classes, Properties, & Methods

Free iOS Development Tutorial

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

  1. Launch Xcode if it isn’t already open.

  2. Go to File > New > Playground.

  3. Under iOS, double–click on Blank.

  4. Navigate into Desktop > Class Files > yourname-iOS App Dev 1 Class.

  5. Save the file as: Classes.playground

  6. Click Create.

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

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.

object vs. traditional

Defining Classes & Custom Methods

  1. Later on, we will need to use objects from UIKit so delete only the var str line.

  2. 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.

  3. 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.

  1. 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.

  2. 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()
  3. 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.

  4. Let’s access the stop method. Type:

    let mustang = Car()
    mustang.start()
    mustang.stop()
  5. 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.

  1. 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.

  2. 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

  3. Let’s set the mustang’s speed to 0 after it stops. Type:

    mustang.start()
    mustang.speed = 10
    mustang.stop()
    mustang.speed = 0
  4. 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()
  5. 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.

  6. To set a speed value from within the stop method, type:

    func stop() {
       self.speed = 0
       print("Screech, halt!")
    }
  7. 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

  8. 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.

  1. 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
    }
  2. 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)
  3. In the class, mouse over the right side of the self.speed = speed line and click the Quick Look eye quick look eye. In the pop-up it says {some 50}, which means that the speed was automatically set to 50.

  4. 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")
    }
  5. 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.

  1. Towards the beginning of the class, add another property for mpg:

    var speed: Int?
    var mpg: Float?
    
    func start() {
  2. 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()
  3. 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.

  4. 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).

  5. 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)
  6. At the bottom of the results sidebar on the right, you should see the amount of gas used: 3.333333

  7. Save the file and keep Xcode open so that we can continue with this file in the next exercise.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn IOS & Web Development

Master IOS Development, Web Development, Coding, and More with Hands-on Training. IOS Development Involves Designing Apps for Apple Mobile Devices with Tools Like Xcode and SwiftUI.

Yelp Facebook LinkedIn YouTube Twitter Instagram