Swift Structures

A structure (struct) groups related data and behavior into one named unit. Structures are value types — when you copy a struct, you get a completely independent copy. Changes to one copy do not affect the other.

The Blueprint Analogy


┌──────────────────────────────────────────────────┐
│  Struct = A house blueprint                      │
│                                                  │
│  Blueprint defines:                              │
│  - Number of rooms  (properties)                 │
│  - How to open door (methods)                    │
│                                                  │
│  Each house built from it is independent.        │
│  Painting one house does NOT paint the others.   │
└──────────────────────────────────────────────────┘

Defining a Struct

struct Car {
    var brand: String
    var speed: Int
    var isElectric: Bool
}

This defines a Car type with three properties. No instance exists yet — this is just the blueprint.

Creating an Instance

var myCar = Car(brand: "Tesla", speed: 200, isElectric: true)
print(myCar.brand)      // Tesla
print(myCar.speed)      // 200
print(myCar.isElectric) // true

Swift automatically generates a memberwise initializer for structs. You pass all property values when creating an instance.

Modifying Properties

myCar.speed = 220
print(myCar.speed)   // 220

Properties of a var struct instance can be changed freely. If the instance is declared with let, no property can change.

Adding Methods

struct Circle {
    var radius: Double

    func area() -> Double {
        return 3.14159 * radius * radius
    }

    func describe() {
        print("Circle with radius \(radius), area \(area())")
    }
}

let c = Circle(radius: 5.0)
c.describe()   // Circle with radius 5.0, area 78.53975

Mutating Methods

struct Counter {
    var count = 0

    mutating func increment() {
        count += 1
    }
}

var c = Counter()
c.increment()
c.increment()
print(c.count)   // 2

Methods that change a struct's own properties must be marked mutating. This is Swift's way of being explicit: the method alters the struct's data.

Value Type Behaviour – Copying

var original = Car(brand: "BMW", speed: 180, isElectric: false)
var copy = original

copy.brand = "Audi"

print(original.brand)   // BMW  ← unchanged
print(copy.brand)       // Audi ← only copy changed

┌──────────────────────────────────────────────────┐
│  original = Car("BMW")   copy = Car("BMW")       │
│                                                  │
│  copy.brand = "Audi"                             │
│                                                  │
│  original → [BMW]   copy → [Audi]                │
│  They are completely independent after copying.  │
└──────────────────────────────────────────────────┘

Computed Properties

struct Rectangle {
    var width: Double
    var height: Double

    var area: Double {
        return width * height
    }

    var perimeter: Double {
        return 2 * (width + height)
    }
}

let rect = Rectangle(width: 8.0, height: 5.0)
print(rect.area)       // 40.0
print(rect.perimeter)  // 26.0

A computed property runs a calculation each time it is accessed. It looks like a stored property but works like a function behind the scenes.

Property Observers

struct BankAccount {
    var balance: Double {
        didSet {
            print("Balance changed to \(balance)")
        }
    }
}

var account = BankAccount(balance: 1000)
account.balance = 1500   // Balance changed to 1500.0

didSet runs automatically after a property's value changes. willSet runs just before the change. Use them to respond to data updates without extra code.

Leave a Comment

Your email address will not be published. Required fields are marked *