Skip to main content
April 1, 2026Noble Desktop Publishing Team/8 min read

Classes, Properties, & Methods

Master Swift Classes and Object-Oriented Programming Fundamentals

Core iOS Development Concepts

Object-Oriented Programming

Learn the foundational programming paradigm that makes Swift powerful. Objects communicate through messages rather than linear execution.

Classes & Methods

Understand how to create blueprints for objects with custom functionality. Classes serve as templates for building app components.

Properties & Parameters

Master data storage within classes and method communication. Properties hold object characteristics while parameters enable dynamic behavior.

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'll master classes—the cornerstone of object-oriented programming and the architectural foundation of Swift development. Classes function as blueprints or templates that encapsulate related functionality, serving as the fundamental building blocks for scalable iOS applications. Understanding classes deeply is essential for any serious iOS developer, as they enable code reusability, maintainability, and the elegant design patterns that separate professional-grade apps from amateur projects.

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.

Object-Oriented Programming

Object-oriented programming (OOP) is a programming paradigm that models real-world concepts as objects containing both data fields (properties that describe the object's characteristics) and associated procedures (methods that define the object's behaviors). This approach revolutionized software development by making code more intuitive, maintainable, and scalable.

Traditional procedural programming follows a linear, top-down approach that quickly becomes unwieldy as applications grow. Code becomes difficult to maintain, reuse, and debug—a nightmare scenario for any development team. Object-oriented programming solves these problems by organizing code into discrete, reusable components that mirror how we naturally think about the world around us.

In Swift's object-oriented model, objects communicate through message passing rather than sequential execution. This creates a more flexible, modular architecture where classes serve as blueprints for creating multiple instances with shared characteristics but unique states. This design pattern is fundamental to iOS development, where you'll constantly work with classes like UIViewController, UIView, and countless others that form the backbone of every iOS application.

object vs. traditional

Traditional vs Object-Oriented Programming

FeatureTraditional ProgrammingObject-Oriented Programming
Code ExecutionLinear, line-by-lineMessage-based between objects
Code ReusabilityLimited reusabilityHigh reusability through classes
MaintenanceBecomes nightmare with scaleOrganized, manageable structure
Code ConnectionsDifficult to establishMeaningful object relationships
Recommended: Object-oriented programming provides better scalability and maintainability for iOS development

Defining Classes & Custom Methods

Now let's put theory into practice by creating our first custom class. We'll build a Car class that demonstrates the core concepts you'll use throughout your iOS development career.

  1. Delete only the var str line, leaving the UIKit import intact—we'll need this framework for future exercises.

  2. Define a class using the class keyword followed by the class name. All class implementation goes within the curly braces. Type the following bold code:

    import UIKit
    
    class Car {
    
    }

    Classes follow noun-based naming conventions since they represent entities or concepts. Think of our Car class like an automotive assembly line template—it defines the structure and capabilities that all car instances will share, while allowing for individual customization in color, features, and performance characteristics.

  3. Remember that methods are functions associated with a specific type. Since classes define custom types, any function within a class becomes a method of that class. Add two essential methods to our Car class:

    class Car {
    
       func start() {
          print("Vroom")
       }
    
       func stop() {
          print("Screech, halt!")
       }
    
    }

    These methods define behaviors that every Car instance will inherit. In real-world iOS development, you'll create methods that handle user interactions, data processing, network requests, and UI updates.

Creating Your First Swift Class

1

Define the Class

Use the 'class' keyword followed by a noun name. Everything goes within curly braces that follow the class declaration.

2

Add Custom Methods

Create functions within the class using 'func' keyword. These become methods associated with the class type.

3

Implement Functionality

Add print statements or other logic within method bodies to define what each method accomplishes.

Class Naming Convention

Classes are usually given noun names. Think of a class like a car frame used for various models - the same template creates different objects with unique characteristics.

Instantiating a Class

With our Car class defined and its methods implemented, we can now create actual objects from this template. The process of creating an object from a class is called instantiation—essentially bringing our blueprint to life as a concrete, usable entity.

  1. Instantiate an object by declaring a constant or variable and assigning it to a class constructor. Create your first Car instance:

    let mustang = Car()

    This creates a specific Car instance named mustang. Each instance maintains its own state while sharing the class's methods and structure. This is the power of object-oriented programming—one class can generate countless unique instances, each with distinct characteristics but identical capabilities.

  2. Access class methods using dot notation with the pattern instanceName.methodName(). Start your mustang:

    let mustang = Car()
    mustang.start()

    This dot notation is fundamental to iOS development—you'll use it constantly when working with UI components, data models, and system frameworks.

  3. Check the results sidebar next to the Car class's start method. You'll see: Vroom

    NOTE: The results sidebar also displays Car next to your method call, confirming which class the method belongs to—a helpful debugging feature during development.

  4. Now invoke the stop method to complete the interaction:

    let mustang = Car()
    mustang.start()
    mustang.stop()
  5. Observe the output Screech, halt! in the results sidebar next to the Car class's stop method.

Objects are instances of classes so the process of bringing an object to life is called instantiation.
Understanding the relationship between classes as templates and objects as specific instances

Object Instantiation Process

1

Create Instance

Declare a constant or variable and set it equal to the class name followed by parentheses.

2

Access Methods

Use dot syntax with the instance name to call methods: instanceName.methodName()

3

Verify Results

Check the results sidebar in Xcode to see method outputs and confirm proper execution.

Properties

Properties are constants or variables declared within a class that represent the characteristics and state of instantiated objects. Well-designed properties make your classes flexible and reusable—essential qualities for maintainable iOS applications. Consider what attributes make each car unique: speed, color, fuel efficiency, or price.

  1. Add a property to track the car's current speed. Insert this near the top of the class:

    class Car {
    
       var speed: Int?
    
       func start() {

    This optional property can be accessed by any Car instance or from within the class's methods. Optionals provide safety when dealing with values that might not exist—a crucial concept we'll explore in depth later.

  2. Set property values using dot notation. Update the mustang's speed after starting:

    let mustang = Car()
    mustang.start()
    mustang.speed = 10
    mustang.stop()

    The syntax pattern is: instanceName.property = value. This external property manipulation works, but isn't the most elegant approach for production code.

  3. Reset the mustang's speed when it stops:

    mustang.start()
    mustang.speed = 10
    mustang.stop()
    mustang.speed = 0
  4. For cleaner, more maintainable code, encapsulate property management within the class itself. Delete both external speed assignments, leaving:

    let mustang = Car()
    mustang.start()
    mustang.stop()
  5. Update the start method to manage its own speed property using the self keyword:

    func start() {
       self.speed = 10
       print("Vroom")
    }

    Within a class, self refers to the current instance. This keyword is essential when setting properties or calling methods from within the class—it ensures you're working with the correct instance's data.

  6. Similarly, update the stop method to reset speed internally:

    func stop() {
       self.speed = 0
       print("Screech, halt!")
    }

    This encapsulation approach keeps related logic together and prevents external code from accidentally putting objects into invalid states.

  7. Display the current speed using string interpolation and forced unwrapping:

    mustang.start()
    print("The speed of the car is \(mustang.speed!) miles per hour")
    mustang.stop()

    The results sidebar displays: The speed of the car is 10 miles per hour

  8. Verify the speed changes by adding another print statement after stopping:

    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")

    You'll see: The speed of the car is 0 miles per hour, confirming that internal property management creates more predictable, reliable behavior.

Using 'self' Within Classes

When working within a class, the instance of that class is called 'self'. Use this keyword to set property values or call methods from within the class itself.

External vs Internal Property Access

FeatureExternal AccessInternal Access
SyntaxinstanceName.propertyself.property
LocationOutside the classInside class methods
EfficiencyManual setting requiredAutomatic within methods
Recommended: Setting property values within class methods is more efficient and maintains better encapsulation

Methods with Parameters

Methods become truly powerful when they accept parameters, allowing external code to provide specific input while maintaining encapsulated logic. This flexibility is essential for creating reusable, adaptable classes that can handle varying requirements—a hallmark of professional iOS development.

  1. Add a parameterized method that accepts a target speed value:

    func stop() {
       self.speed = 0
       print("Screech, halt!")
    }
    
    func accelerateTo(speed: Int) {
       self.speed = speed
    }

    This method provides controlled access to the speed property while maintaining the class's responsibility for managing its own state.

  2. Call the new method with a specific speed argument:

    print("The speed of the car is \(mustang.speed!) miles per hour")
    
    mustang.accelerateTo(speed: 50)

    Swift's parameter labels make method calls self-documenting, improving code readability—crucial for team development environments.

  3. Verify the parameter was processed correctly by hovering over the self.speed = speed line and clicking the Quick Look eye quick look eye. The popup shows {some 50}, confirming the speed was updated.

  4. Add user feedback to the accelerateTo method:

    func accelerateTo(speed: Int) {
       self.speed = speed
       print("The speed is now \(self.speed!) miles per hour")
    }

    The results sidebar confirms: The speed is now 50 miles per hour

Methods vs Functions

Methods are functions that exist within a class. Like functions, methods can accept parameters and return data, but they operate on class instances.

Creating Parameterized Methods

1

Define Method Signature

Include parameter name and type within parentheses after the method name.

2

Implement Method Body

Use the parameter value within the method to modify properties or perform calculations.

3

Call with Arguments

Provide specific values when calling the method using the parameter label syntax.

Methods with Return Values

Methods that return values enable classes to perform calculations and provide results to calling code, creating powerful, reusable functionality. This capability is fundamental to building sophisticated iOS applications that process data, perform computations, and integrate with external services.

  1. Add a property to track fuel efficiency—a realistic attribute for any vehicle:

    var speed: Int?
    var mpg: Float?
    
    func start() {
  2. Set the mpg for your specific car instance, demonstrating how different objects can have unique property values:

    let mustang = Car()
    mustang.mpg = 30.0
    mustang.start()

    This illustrates object-oriented programming's power—multiple Car instances could have different mpg values, representing various vehicle types while sharing the same basic functionality.

  3. Create a method that calculates and returns fuel consumption based on distance traveled:

    func accelerateTo(speed: Int) {
          self.speed = speed
          print("The speed is now \(self.speed!) miles per hour")
       }
    
       func gasUsed(milesDriven: Float) -> Float {
    
       }
    
    }

    The -> Float syntax specifies the return type, establishing a contract that this method will provide a Float value to its caller.

  4. Implement the calculation logic and return the result:

    func gasUsed(milesDriven: Float) -> Float {
       let gas = milesDriven / mpg!
       return gas
    }

    This method demonstrates how classes can encapsulate complex calculations while providing simple interfaces for external code to use.

  5. Use the method's return value by capturing it in a constant:

    mustang.accelerateTo(speed: 50)
    
    let theGasUsed = mustang.gasUsed(milesDriven: 100.0)

    This pattern—calling a method and storing its result—is fundamental to iOS development, where you'll constantly work with data returned from network calls, user inputs, and system APIs.

  6. The results sidebar displays the calculated fuel consumption: 3.333333 gallons for 100 miles at 30 mpg.

  7. Save your file and keep Xcode open for the next exercise, where we'll build upon these foundational concepts to create more sophisticated class hierarchies and explore advanced object-oriented features.

Implementing Return Methods

1

Specify Return Type

Add arrow syntax and return type after method parameters to indicate what data type the method returns.

2

Calculate and Store

Create constants or variables within the method to perform calculations using class properties.

3

Return Result

Use the 'return' keyword to send the calculated value back to the method caller.

Object-Oriented Benefits

The mpg property can be set differently for each car instance. This demonstrates how object-oriented programming enables reusable code with customizable characteristics.

Key Takeaways

1Object-oriented programming uses message-passing between objects instead of linear code execution, making applications more maintainable and scalable
2Classes serve as blueprints or templates that define the structure and behavior of objects in Swift applications
3Instantiation is the process of creating specific object instances from class templates using constant or variable declarations
4Properties are constants or variables declared within classes that represent object characteristics and can be accessed using dot syntax
5Methods are functions that belong to classes and can accept parameters, modify properties, and return values to enable dynamic behavior
6The 'self' keyword refers to the current instance within a class and is used to access properties and methods internally
7Setting property values within class methods is more efficient than external manipulation and maintains better code organization
8Swift classes support parameterized methods and return values, enabling complex calculations and data manipulation within object-oriented structures

RELATED ARTICLES