Class vs. Struct in Swift Programming: What’s the Difference?

Understanding the Key Differences in Just a Few Minutes

Arc Sosangyo
5 min readNov 5, 2024
Photo by Олег Мороз on Unsplash

At first glance, structs and classes seem to work the same way, which can be pretty confusing if you’re new to programming. Or maybe I was the only one who felt confused at first! Anyway, let’s talk about the differences between classes and structs.

Imagine they’re like two very similar superheroes, each with unique powers, but both in the business of bundling data and functionality together.

1. Value vs. Reference Types

  • Structs are value types, meaning when you assign a struct to a new variable, Swift makes a copy of that struct. So, changes to one instance don’t affect the other.
  • Classes are reference types, meaning when you assign a class instance to another variable, it’s like giving them both the same “link” to the same object in memory. Changes to one will affect the other.

Here’s an example of a Struct being a value type:

struct CloneTrooper {
var name: String
var level: Int
}

// Create a Clone Trooper
var originalTrooper = CloneTrooper(name: "CT-101", level: 1)

// Make a copy
var copiedTrooper = originalTrooper

// Change the level of the copied trooper…

--

--

Arc Sosangyo
Arc Sosangyo

Written by Arc Sosangyo

Arc is an iOS Dev and app publisher, a former IT manager who transitioned to iOS engineering, and a big fan of AI, coding, science, history, and philosophy.

No responses yet