Swift / Object-Oriented Programming in Swift

Exploring Structures and Their Differences

In this tutorial, we'll explore what structures are in Swift, and how they differ from classes. We'll delve into the concept of value types and reference types.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers OOP concepts like classes, structures, and protocols in Swift.

Exploring Structures and Their Differences in Swift

1. Introduction

Brief explanation of the tutorial's goal

This tutorial aims to provide a comprehensive understanding of what structures (or structs) are in Swift, how they work, and how they differ from classes.

What the user will learn

By the end of this tutorial, you will be able to:
- Understand the concept of structures and classes in Swift.
- Differentiate between reference types and value types.
- Implement structures and classes in your Swift programs.

Prerequisites

Basic knowledge of Swift programming is recommended to make the most of this tutorial.

2. Step-by-Step Guide

Understanding Structures in Swift

Structures, or structs, are one of the basic building blocks in Swift. They allow you to encapsulate related properties and behaviors.

struct Student {
    var name: String
    var age: Int
}

In this example, Student is a structure that has two properties, name and age.

Understanding Classes in Swift

Classes are similar to structs but come with additional features like inheritance.

class Teacher {
    var name: String
    var subject: String

    init(name: String, subject: String) {
        self.name = name
        self.subject = subject
    }
}

In this example, Teacher is a class that also has two properties, name and subject.

Differences between Structures and Classes

The primary difference between structs and classes lies in the way they are handled in memory. Structs are value types and Classes are reference types.

Value Types

When you assign a struct to a new variable or pass it to a function, Swift creates a new copy of it.

var student1 = Student(name: "John", age: 20)
var student2 = student1
student2.name = "Jane"

print(student1.name) // Output: John
print(student2.name) // Output: Jane

Even though we change student2.name to "Jane", student1.name remains "John".

Reference Types

Classes, on the other hand, are reference types. When you assign a class to a new variable or pass it to a function, Swift creates a new reference to the same instance.

var teacher1 = Teacher(name: "Mr. Smith", subject: "Math")
var teacher2 = teacher1
teacher2.name = "Mr. Johnson"

print(teacher1.name) // Output: Mr. Johnson
print(teacher2.name) // Output: Mr. Johnson

Here, when we change teacher2.name to "Mr. Johnson", teacher1.name also changes to "Mr. Johnson".

3. Code Examples

Struct Example

struct Car {
    var make: String
    var model: String
}
var car1 = Car(make: "Honda", model: "Civic")
var car2 = car1
car2.model = "Accord"

print(car1.model) // Output: Civic
print(car2.model) // Output: Accord

Class Example

class Truck {
    var make: String
    var model: String

    init(make: String, model: String) {
        self.make = make
        self.model = model
    }
}
var truck1 = Truck(make: "Ford", model: "F-150")
var truck2 = truck1
truck2.model = "Ranger"

print(truck1.model) // Output: Ranger
print(truck2.model) // Output: Ranger

4. Summary

In this tutorial, we explored structures and classes in Swift. We learned about the difference between value types (structs) and reference types (classes), and how they behave differently when copied or passed around in your code.

5. Practice Exercises

  1. Define a struct and a class for a Book with title and author properties. Create two instances and observe the behavior when you modify one.
  2. Define a struct and a class for a Person with name, age, and address properties. Implement a function that takes a person and changes the address. Observe the behavior for structs and classes.

Note: To solve these exercises, you can follow the same pattern as the examples provided in the tutorial.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Image Converter

Convert between different image formats.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help